PageSourceSearch

https://www.trybased.com/static/js/5739.e53b2eb1.chunk.js

js trybased.com collected 2026-09-24 14:56:03 UTC 988,381 bytes, 2 lines download raw bytes

1"use strict";(self.webpackChunkknowledge_base_saas=self.webpackChunkknowledge_base_saas||[]).push([[5739],{94659(e,t,n){n.d(t,{A:()=>l});n(65043);var r=n(77819),o=n(36210),a=n(39292),i=n(66630),s=n(70579);const l=e=>{let t=e.status,n=e.error,l=e.className,d=void 0===l?"":l;return t?"indexing"===t?(0,s.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800 ".concat(d),title:"Updating search so AI and workspace search use your latest text.",children:[(0,s.jsx)(i.y$,{size:"sm",className:"!h-3 !w-3"}),(0,s.jsx)(a.A,{className:"w-3 h-3 shrink-0"}),"AI search\u2026"]}):"failed"===t?(0,s.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 ".concat(d),title:n||"Search index update failed.",children:[(0,s.jsx)(r.A,{className:"w-3 h-3 shrink-0"}),"Search index failed"]}):"ready"===t?(0,s.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-600 ".concat(d),title:"This document is ready for AI and workspace search.",children:[(0,s.jsx)(o.A,{className:"w-3 h-3 shrink-0"}),"AI Ready"]}):null:null}},27019(e,t,n){n.d(t,{A:()=>oe});var r=n(89379),o=n(5544),a=n(65043),i=n(97950),s=n(47874),l=n(50781),d=n(61064),c=n(4596),u=n(56099),m=n(37719),p=n(5244),g=n(65469),h=n(14939),f=n(36210),y=n(92382),v=n(38326),x=n(26405),b=n(75088),w=n(72313),k=n(86376),A=n(69807),j=n(41680),N=n(94965),C=n(687),S=n(55731),E=n(70067),I=n(3308),D=n(65727),P=n(35327),T=n(10629),R=n(71360),O=n(88306),F=n(9855),L=n(82300),_=n(37322),U=n(59395),M=n(55472),z=n(96822),B=n(1862),W=n(60930),V=n(92339),J=n(92829),q=n(23524),H=n(95523),G=n(15003),K=n(31928),Q=n(17070),Y=n(98688),Z=n(78324),$=n(70579);function X(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:50;return e?"string"!==typeof e?"Invalid format":e.length<=t?e:"".concat(e.substring(0,t),"..."):null}function ee(e){let t=e.currentDoc;const n=(0,a.useState)(!1),r=(0,o.A)(n,2),s=r[0],l=r[1],c=(0,a.useState)({top:0,left:0}),u=(0,o.A)(c,2),p=u[0],g=u[1],h=(0,a.useRef)(null),f=!(null===(y=t)||void 0===y||!y.isEncrypted)&&!y.isDecrypted&&!y._isDecrypted&&!(y.userEncryptedResult||y.encryptedResult);var y;const v=function(e){return null!==e&&void 0!==e&&e.userEncryptedResult?{fieldName:"userEncryptedResult",blob:e.userEncryptedResult,type:"dual"}:null!==e&&void 0!==e&&e.encryptedResult?{fieldName:"encryptedResult",blob:e.encryptedResult,type:"legacy"}:null}(t),x=()=>{if(h.current){const e=h.current.getBoundingClientRect();g({top:e.bottom+8,left:Math.max(16,e.left+e.width/2-160)})}l(!0)};return null!==t&&void 0!==t&&t.isEncrypted||null!==t&&void 0!==t&&t.isDecrypted||null!==t&&void 0!==t&&t._isDecrypted?f?(0,$.jsxs)("div",{className:"relative",children:[(0,$.jsxs)("span",{ref:h,className:"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium text-red-700 bg-red-100 border border-red-300 rounded-full cursor-help",onMouseEnter:x,onMouseLeave:()=>l(!1),children:[(0,$.jsx)(m.A,{className:"w-3.5 h-3.5 text-red-600"}),"Unencrypted"]}),s&&(0,i.createPortal)((0,$.jsxs)("div",{className:"fixed z-[9999] w-72 p-3 bg-red-50 border border-red-200 rounded-lg shadow-xl text-xs",style:{to
1p:p.top,left:p.left},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[(0,$.jsxs)("div",{className:"font-semibold text-red-800 mb-2 flex items-center gap-1.5",children:[(0,$.jsx)(m.A,{className:"w-4 h-4"}),"Security Warning"]}),(0,$.jsx)("p",{className:"text-red-700 mb-2",children:"This document is marked as encrypted but contains unencrypted content in the database."}),(0,$.jsxs)("div",{className:"text-red-600 text-[10px] space-y-1",children:[(0,$.jsx)("div",{children:(0,$.jsx)("strong",{children:"Leaking fields:"})}),(null===t||void 0===t?void 0:t.editorJson)&&""!==t.editorJson&&"{}"!==t.editorJson&&(0,$.jsx)("div",{className:"pl-2",children:"? editorJson present"}),(null===t||void 0===t?void 0:t.editorHtml)&&""!==t.editorHtml&&"<p></p>"!==t.editorHtml&&(0,$.jsx)("div",{className:"pl-2",children:"? editorHtml present"}),(null===t||void 0===t?void 0:t.textContent)&&""!==t.textContent&&"[Encrypted Content]"!==t.textContent&&(0,$.jsxs)("div",{className:"pl-2",children:['? textContent: "',t.textContent.substring(0,30),'..."']})]})]}),document.body)]}):(0,$.jsxs)("div",{className:"relative",children:[(0,$.jsxs)("span",{ref:h,className:"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium text-emerald-700 bg-emerald-50 border border-emerald-200 rounded-full cursor-help",onMouseEnter:x,onMouseLeave:()=>l(!1),children:[(0,$.jsx)(D.A,{className:"w-3.5 h-3.5 text-emerald-600"}),"Encrypted"]}),s&&(0,i.createPortal)((0,$.jsxs)("div",{className:"fixed z-[9999] w-80 p-3 bg-white border border-gray-200 rounded-lg shadow-xl text-xs",style:{to
1p:p.top,left:p.left},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[(0,$.jsxs)("div",{className:"font-semibold text-gray-800 mb-2 flex items-center gap-1.5",children:[(0,$.jsx)(D.A,{className:"w-4 h-4 text-emerald-600"}),"End-to-End Encryption"]}),(0,$.jsx)("p",{className:"text-gray-600 mb-3",children:"Content is encrypted client-side using AES-256-GCM before being sent to our servers. Only you (and shared workspaces) can decrypt it."}),v&&(0,$.jsxs)("div",{className:"bg-gray-50 rounded p-2 mb-2",children:[(0,$.jsx)("div",{className:"text-[10px] text-gray-500 mb-1 font-medium",children:"How document appears in database:"}),(0,$.jsxs)("code",{className:"text-[10px] text-gray-700 break-all font-mono block bg-white p-1.5 rounded border border-gray-200",children:['"',X(v.blob,100),'"']})]}),((null===t||void 0===t?void 0:t.isDecrypted)||(null===t||void 0===t?void 0:t._isDecrypted))&&(0,$.jsxs)("div",{className:"flex items-center gap-1.5 text-[10px] text-emerald-600",children:[(0,$.jsx)("span",{className:"w-1.5 h-1.5 bg-emerald-500 rounded-full"}),"Document is currently in decrypted state in order to make content visible."]})]}),document.body)]}):(0,$.jsxs)("div",{className:"relative",children:[(0,$.jsxs)("span",{ref:h,className:"inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium text-slate-600 bg-slate-100 border border-slate-300 rounded-full cursor-help",onMouseEnter:x,onMouseLeave:()=>l(!1),children:[(0,$.jsx)(d.A,{className:"w-3.5 h-3.5 text-slate-500"}),"Unencrypted"]}),s&&(0,i.createPortal)((0,$.jsxs)("div",{className:"fixed z-[9999] w-72 p-3 bg-slate-50 border border-slate-200 rounded-lg shadow-xl text-xs",style:{to
1p:p.top,left:p.left},onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[(0,$.jsxs)("div",{className:"font-semibold text-slate-800 mb-2 flex items-center gap-1.5",children:[(0,$.jsx)(d.A,{className:"w-4 h-4 text-slate-600"}),"Unencrypted"]}),(0,$.jsx)("p",{className:"text-slate-600",children:"This document is stored unencrypted. Content is visible to anyone with access."})]}),document.body)]})}const te=[{label:"1 hour",hours:1},{label:"24 hours",hours:24},{label:"7 days",hours:168}];function ne(e){if(!e)return null;const t=new Date(e);if(Number.isNaN(t.getTime()))return null;const n=t.getTime()-Date.now();if(n<=0)return null;const r=t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}),o=Math.round(n/36e5);if(o<1){const e=Math.max(1,Math.round(n/6e4));return"Expires in ".concat(e," min (").concat(r,")")}if(o<48)return"Expires in ".concat(o,"h (").concat(r,")");const a=Math.round(o/24);return"Expires in ".concat(a,"d (").concat(r,")")}function re(e){let t=e.currentDoc,n=e.onShare,s=e.getEmailPlainText;const l=(0,a.useState)(!1),d=(0,o.A)(l,2),c=d[0],m=d[1],p=(0,a.useState)(null),g=(0,o.A)(p,2),x=g[0],k=g[1],A=(0,a.useState)(!1),j=(0,o.A)(A,2),N=j[0],C=j[1],E=(0,a.useState)(!1),I=(0,o.A)(E,2),D=I[0],T=I[1],R=(0,a.useState)(null),F=(0,o.A)(R,2),L=F[0],_=F[1],U=(0,a.useState)({top:0,right:0}),B=(0,o.A)(U,2),W=B[0],J=B[1],q=(0,a.useState)(!1),H=(0,o.A)(q,2),G=H[0],K=H[1],Q=(0,a.useRef)(null),X=(0,a.useRef)(null),ee=(0,a.useState)(24),re=(0,o.A)(ee,2),oe=re[0],ae=re[1],ie=(0,a.useState)(null),se=(0,o.A)(ie,2),le=se[0],de=se[1],ce=(0,a.useState)(null),ue=(0,o.A)(ce,2),me=ue[0],pe=ue[1],ge=(0,a.useState)(!1),he=(0,o.A)(ge,2),fe=he[0],ye=he[1],ve=(0,a.useState)(!1),xe=(0,o.A)(ve,2),be=xe[0],we=xe[1],ke=(0,a.useCallback)(()=>Array.isArray(null===t||void 0===t?void 0:t.workspaceIds)&&t.workspaceIds.length>0?t.workspaceIds[0]:(null===t||void 0===t?void 0:t.workspaceId)||null,[null===t||void 0===t?void 0:t.workspaceIds,null===t||void 0===t?void 0:t.workspaceId]),Ae=(0,a.useCallback)(async e=>{const n=ke();if(!n)throw new Error("This document is not in a workspace yet.");const o=z.j2.currentUser;if(!o)throw new Error("Please sign in again to manage links.");const a=await o.getIdToken(),i=await fetch("".concat("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/createShareableLink","?knowledgeBaseId=").concat(encodeURIComponent(n)),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(a)},body:JSON.stringify((0,r.A)((0,r.A)({documentId:t.id},e),{},{hideTimeEntryTimestamps:!(0,Z.a8)()}))});if(!i.ok){const e=await i.text();let t="";try{var s;t=(null===(s=JSON.parse(e))||void 0===s?void 0:s.error)||""}catch(l){}throw new Error(t||"Request failed (".concat(i.status,")"))}return i.json()},[null===t||void 0===t?void 0:t.id,ke]),je=(0,a.useCallback)(e=>{const t=e.linkId;k("string"===typeof e.shareableLink&&e.shareableLink||"".concat(window.location.origin,"/shared/").concat(t));const n=ne(e.expiryDate);!0===e.rawTextEnabled&&n?(de("".concat(window.location.origin,"/raw/").concat(t)),pe(e.expiryDate)):(de(null),pe(null))},[]),Ne=(0,a.useCallback)(()=>null!==t&&void 0!==t&&t.id?(X.current||(X.current=(async()=>{T(!0),_(null);try{const n=(0,M.rJ)(z.db,"shareableLinks"),o=(0,M.P)(n,(0,M._M)("documentId","==",t.id),(0,M._M)("isPublic","==",!0),(0,M.AB)(1)),a=await(0,M.GG)(o);if(!a.empty){const e=a.docs[0].data(),t=await Ae({linkId:e.linkId,isPublic:!1!==e.isPublic,expiryDate:e.expiryDate||null,emailNotifications:!1!==e.emailNotifications,emailOnOpen:!!e.emailOnOpen,commentsEnabled:!!e.commentsEnabled,enabledViews:e.enabledViews||"both",shareAsReport:!!e.shareAsReport,reportIntroduction:e.reportIntroduction||"",reportCoverButtonColor:e.reportCoverButtonColor||void 0,agentConfig:e.agentConfig||void 0,rawTextEnabled:!0===e.rawTextEnabled}),n=(0,r.A)((0,r.A)((0,r.A)({},e),t),{},{linkId:t.linkId||e.linkId});return je(n),"string"===typeof n.shareableLink&&n.shareableLink||"".concat(window.location.origin,"/shared/").concat(n.linkId)}const i=await Ae({isPublic:!0,expiryDate:null,emailNotifications:!0,commentsEnabled:!1,enabledViews:"both",agentConfig:{enabled:!0,theme:"default",position:"bottom-right",size:"medium",branding:!0,visitorPdfAccessForChat:!0}}),s="string"===typeof i.shareableLink&&i.shareableLink||"".concat(window.location.origin,"/shared/").concat(i.linkId);k(s),de(null),pe(null);try{await navigator.clipboard.writeText(s),C(!0),setTimeout(()=>C(!1),2e3)}catch(e){}return s}catch(n){return"permission-denied"!==(null===n||void 0===n?void 0:n.code)&&console.error("Error ensuring document share link:",n),k(null),de(null),pe(null),_((null===n||void 0===n?void 0:n.message)||"Could not create a public link."),null}finally{T(!1),X.current=null}})()),X.current):(k(null),de(null),pe(null),_(null),Promise.resolve(null)),[null===t||void 0===t?void 0:t.id,je,Ae]),Ce=(0,a.useCallback)(()=>{m(e=>{const t=!e;if(t&&(Ne(),Q.current)){const e=Q.current.getBoundingClientRect();J({top:e.bottom+8,right:window.innerWidth-e.right})}return t})},[Ne]),Se=(0,a.useCallback)(async()=>
1{if(x)try{await navigator.clipboard.writeText(x),C(!0),setTimeout(()=>C(!1),2e3)}catch(e){console.error("Failed to copy link:",e)}},[x]),Ee=(0,a.useCallback)(async()=>{if(null!==t&&void 0!==t&&t.id&&!fe){ye(!0);try{const t=new Date(Date.now()+60*oe*60*1e3).toISOString(),n=await Ae({isPublic:!0,expiryDate:t,rawTextEnabled:!0}),r="".concat(window.location.origin,"/raw/").concat(n.linkId);de(r),pe(n.expiryDate||t);try{await navigator.clipboard.writeText(r),we(!0),setTimeout(()=>we(!1),2e3)}catch(e){}V.Ay.success("Temporary AI link created and copied")}catch(n){console.error("Failed to create raw AI link:",n),V.Ay.error(n.message||"Failed to create temporary AI link")}finally{ye(!1)}}},[null===t||void 0===t?void 0:t.id,fe,oe,Ae]),Ie=(0,a.useCallback)(async()=>{if(le)try{await navigator.clipboard.writeText(le),we(!0),setTimeout(()=>we(!1),2e3)}catch(e){console.error("Failed to copy raw link:",e)}},[le]),De=(0,a.useCallback)(async()=>{if(null!==t&&void 0!==t&&t.id&&!fe){ye(!0);try{await Ae({rawTextEnabled:!1}),de(null),pe(null),V.Ay.success("Temporary AI access revoked")}catch(e){console.error("Failed to revoke raw AI link:",e),V.Ay.error(e.message||"Failed to revoke AI access")}finally{ye(!1)}}},[null===t||void 0===t?void 0:t.id,fe,Ae]),Pe=(0,a.useCallback)(async()=>{if(!G){K(!0);try{const e=(null===t||void 0===t?void 0:t.title)||(null===t||void 0===t?void 0:t.fileName)||"Document",n="function"===typeof s?s():"",r=(0,Y.n5)((0,Y.MF)(n||(0,Y.MH)(t,"",{title:e})),e),o=await(0,Y.zn)({title:e,body:r});if(!o.opened)return void V.Ay.error("empty"===o.reason?"Add some document content before opening email.":"Could not open your email app.");m(!1),o.copiedToClipboard?(0,V.Ay)("Full letter copied - paste it into the email (Cmd+V).",{duration:6e3}):o.truncated?(0,V.Ay)("Opened in your email app with a shortened body. For long letters, attach a PDF instead.",{duration:5e3}):V.Ay.success("Opened in your email app")}finally{K(!1)}}},[G,t,s]);(0,a.useEffect)(()=>{if(!c)return;const e=e=>{const t=document.querySelector('[data-doc-share-menu="true"]');!Q.current||Q.current.contains(e.target)||t&&t.contains(e.target)||m(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[c]);const Te=(0,$.jsxs)("div",{role:"menu","data-doc-share-menu":"true",className:"fixed min-w-[300px] w-max max-w-[min(100vw-2rem,400px)] bg-white border border-gray-200 rounded-md shadow-lg z-[9999] overflow-hidden",style:{top:"".concat(W.top,"px"),right:"".concat(W.right,"px")},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)("div",{className:"px-4 py-3 border-b border-gray-200",children:D?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,$.jsx)(S.A,{className:"h-4 w-4 text-gray-700"}),(0,$.jsx)("div",{className:"text-sm font-medium text-gray-900",children:"Public link"})]}),(0,$.jsx)("p",{className:"text-xs text-gray-500",children:"Getting public link..."})]}):x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,$.jsx)(S.A,{className:"h-4 w-4 text-gray-700"}),(0,$.jsx)("div",{className:"text-sm font-medium text-gray-900",children:"Public link"})]}),(0,$.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,$.jsxs)("div",{className:"flex items-center gap-2",children:[(0,$.jsx)("input",{type:"text",value:x,readOnly:!0,className:"flex-1 px-2 py-1.5 text-xs border border-gray-200 rounded bg-gray-50 truncate"}),(0,$.jsx)("button",{type:"button",onClick:Se,className:"p-2 rounded transition-colors hover:bg-gray-100",title:"Copy to clipboard",children:N?(0,$.jsx)(f.A,{className:"w-4 h-4 text-green-500"}):(0,$.jsx)(w.A,{className:"w-4 h-4 text-gray-600"})})]}),N&&(0,$.jsx)("span",{className:"text-xs text-green-600 block",children:"Copied!"})]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,$.jsx)(S.A,{className:"h-4 w-4 text-gray-400"}),(0,$.jsx)("div",{className:"text-sm font-medium text-gray-500",children:"No public link"})]}),(0,$.jsx)("p",{className:"text-xs text-gray-500",children:L?"".concat(L," Open sharing settings to try again."):"Open sharing settings to create a shareable link."})]})}),(0,$.jsxs)("div",{className:"border-t border-gray-200",children:[(0,$.jsxs)("button",{type:"button",role:"menuitem",onClick:Pe,disabled:G,className:"w-full flex items-center justify-between px-4 py-2.5 text-sm font-medium text-gray-900 hover:bg-gray-50 disabled:opacity-50",title:"Open this document in your default email app",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(P.A,{className:"h-4 w-4 text-gray-700"}),G?"Opening email...":"Open in email"]}),(0,$.jsx)(v.A,{className:"h-4 w-4 text-gray-300"})]}),(0,$.jsx)("p",{className:"px-4 pb-2.5 text-xs text-gray-500 -mt-1",children:"Drafts the letter in Gmail, Mail, or Outlook (your default app)."})]}),(0,$.jsxs)("div",{className:"px-4 py-3 border-t border-gray-200",children:[(0,$.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,$.jsx)(h.A,{className:"h-4 w-4 text-gray-700"}),(0,$.jsx)("div",{className:"text-sm font-medium text-gray-900",children:"Temporary AI link"})]}),(0,$.jsx)("p",{className:"text-xs text-gray-500",children:"A short-lived link that returns this document as plain text, so tools like Claude, ChatGPT, and Cursor can read it. Expires automatically."}),le?(0,$.jsxs)("div",{className:"mt-2 space-y-2",children:[(0,$.jsxs)("div",{className:"flex items-center gap-2",children:[(0,$.jsx)("input",{type:"text",value:le,readOnly:!0,className:"flex-1 px-2 py-1.5 text-xs border border-gray-200 rounded bg-gray-50 truncate"}),(0,$.jsx)("button",{type:"button",onClick:Ie,className:"p-2 rounded transition-colors hover:bg-gray-100",title:"Copy AI link",children:be?(0,$.jsx)(f.A,{className:"w-4 h-4 text-green-500"}):(0,$.jsx)(w.A,{className:"w-4 h-4 text-gray-600"})})]}),ne(me)&&(0,$.jsxs)("p",{className:"text-xs text-gray-500 flex items-center gap-1",children:[(0,$.jsx)(b.A,{className:"h-3 w-3"}),ne(me)]}),(0,$.jsx)("button",{type:"button",onClick:De,disabled:fe,className:"text-xs text-red-600 hover:text-red-700 disabled:opacity-50",children:fe?"Working?":"Revoke AI access"})]}):(0,$.jsxs)("div",{className:"mt-2 flex items-center gap-2",children:[(0,$.jsx)("select",{value:oe,onChange:e=>ae(Number(e.target.value)),disabled:fe,className:"px-2 py-1.5 text-xs border border-gray-200 rounded bg-white disabled:opacity-50",title:"How long the link stays active",children:te.map(e=>(0,$.jsx)("option",{value:e.hours,children:e.label},e.hours))}),(0,$.jsx)("button",{type:"button",onClick:Ee,disabled:fe,className:"flex-1 px-3 py-1.5 text-xs font-medium text-white bg-gray-900 rounded hover:bg-gray-800 disabled:opacity-50 flex items-center justify-center gap-1.5",children:fe?"Creating?":(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h.A,{className:"h-3.5 w-3.5"}),"Create AI link"]})})]})]}),(0,$.jsx)("div",{className:"border-t border-gray-200",children:(0,$.jsxs)("button",{type:"button",role:"menuitem",onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),n(t.id),setTimeout(()=>m(!1),100)},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50",title:"Open sharing settings",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(u.A,{className:"h-4 w-4 text-gray-500"}
1),"Sharing settings"]}),(0,$.jsx)(v.A,{className:"h-4 w-4 text-gray-300"})]})})]});return(0,$.jsxs)("div",{className:"relative",children:[(0,$.jsxs)("button",{ref:Q,type:"button",onClick:Ce,className:"cursor-pointer px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded transition-colors duration-150 flex items-center gap-2",title:"Share document","aria-haspopup":"menu","aria-expanded":c,children:[(0,$.jsx)(O.A,{className:"w-4 h-4 pointer-events-none","aria-hidden":!0}),(0,$.jsx)("span",{className:"pointer-events-none",children:"Share"}),(0,$.jsx)(y.A,{className:"h-3.5 w-3.5 text-gray-400 pointer-events-none","aria-hidden":!0})]}),c&&(0,i.createPortal)(Te,document.body)]})}function oe(e){let t=e.currentDoc,n=e.onCategoryChange,r=e.categoryPresets,m=void 0===r?[]:r,h=e.onWorkspaceChange,f=e.availableWorkspaces,S=void 0===f?[]:f,P=e.workspaceList,O=void 0===P?[]:P,M=e.onDelete,z=e.onCreateWorkspace,Y=e.onNavigateBack,Z=e.onShare,X=e.versionControlEnabled,te=void 0!==X&&X,ne=e.versionControlReady,oe=void 0===ne||ne,ae=e.pdfExportEnabled,ie=void 0!==ae&&ae,se=e.onExportPdf,le=e.isGeneratingPdf,de=void 0!==le&&le,ce=e.paymentConfigOpen,ue=void 0!==ce&&ce,me=e.setPaymentConfigOpen,pe=e.paymentConfigUpdating,ge=void 0!==pe&&pe,he=e.updateDocumentPaymentConfig,fe=e.paymentFixedAmountEditing,ye=void 0===fe?null:fe,ve=e.setPaymentFixedAmountEditing,xe=e.paymentSubscriptionAmountEditing,be=void 0===xe?null:xe,we=e.setPaymentSubscriptionAmountEditing,ke=e.paymentSubscriptionEnabledEffective,Ae=e.onPlacePaymentButton,je=(e.paymentButtonRef,e.docActionsContainerRef),Ne=e.setDocActionsContainerReady,Ce=e.minimalUI,Se=void 0!==Ce&&Ce,Ee=e.onDuplicate,Ie=e.onArchive,De=e.documentSignaturesEnabled,Pe=void 0!==De&&De,Te=e.onAddField,Re=e.onSign,Oe=e.timerEnabled,Fe=void 0!==Oe&&Oe,Le=e.timerContent,_e=void 0===Le?null:Le,Ue=e.onTimerOpen,Me=e.voiceEnabled,ze=void 0!==Me&&Me,Be=e.onVoiceClick,We=e.sopEnhancementEnabled,Ve=void 0!==We&&We,Je=e.onAIEnhancementsClick,qe=e.formsEnabled,He=void 0!==qe&&qe,Ge=e.onFormsClick,Ke=e.templateFillEnabled,Qe=void 0!==Ke&&Ke,Ye=e.onTemplateFillClick,Ze=e.envVaultEnabled,$e=void 0!==Ze&&Ze,Xe=e.onEnvVaultClick,et=e.stripeIntegrationConnected,tt=void 0!==et&&et,nt=e.autoTitleEnabled,rt=void 0!==nt&&nt,ot=e.autoCategoryEnabled,at=void 0!==ot&&ot,it=e.pexelsEnabled,st=void 0!==it&&it,lt=e.abilitiesButtonRef,dt=e.actionsDropdownOpen,ct=e.setActionsDropdownOpen,ut=e.onOpenExternalChatgpt,mt=e.onOpenExternalClaude,pt=e.getEmailPlainText,gt=e.showBackLink,ht=void 0===gt||gt,ft=e.documentLockEnabled,yt=void 0!==ft&&ft,vt=e.onLockDocument,xt=e.onUnlockDocument,bt=e.metadataOnly,wt=void 0!==bt&&bt;const kt=(0,a.useCallback)(()=>{const e=[];if(null!==t&&void 0!==t&&t.isNew)return null!==t&&void 0!==t&&t.workspaceIds&&Array.isArray(t.workspaceIds)&&t.workspaceIds.forEach(t=>{if(null!==t&&void 0!==t){const n=null===O||void 0===O?void 0:O.find(e=>e.id===t);n?e.push(n.name):e.push("Default Workspace")}}),e;if(null!==t&&void 0!==t&&t.workspaceIds&&Array.isArray(t.workspaceIds)&&t.workspaceIds.forEach(t=>{if(null!==t&&void 0!==t){const n=null===O||void 0===O?void 0:O.find(e=>e.id===t);n&&e.push(n.name)}}),null!==t&&void 0!==t&&t.workspace&&"None"!==t.workspace&&""!==t.workspace)if((null===O||void 0===O?void 0:O.length)>0){O.some(e=>e.name===t.workspace)&&!e.includes(t.workspace)&&e.push(t.workspace)}else e.includes(t.workspace)||e.push(t.workspace);return e.length>0?e:["Default"]},[t,O]),At=(0,a.useState)((null===t||void 0===t?void 0:t.category)||""),jt=(0,o.A)(At,2),Nt=jt[0],Ct=jt[1],St=(0,a.useState)(!1),Et=(0,o.A)(St,2),It=Et[0],Dt=Et[1],Pt=(0,a.useState)(!1),Tt=(0,o.A)(Pt,2),Rt=Tt[0],Ot=Tt[1],Ft=(0,a.useState)(""),Lt=(0,o.A)(Ft,2),_t=Lt[0],Ut=Lt[1],Mt=(0,a.useState)(null),zt=(0,o.A)(Mt,2),Bt=zt[0],Wt=zt[1],Vt=(0,a.useState)(!1),Jt=(0,o.A)(Vt,2),qt=Jt[0],Ht=Jt[1],Gt=(0,a.useState)(!1),Kt=(0,o.A)(Gt,2),Qt=Kt[0],Yt=Kt[1],Zt=(0,a.useState)(null),$t=(0,o.A)(Zt,2),Xt=$t[0],en=$t[1],tn=(0,a.useState)(!1),nn=(0,o.A)(tn,2),rn=nn[0],on=nn[1],an=(0,a.useState)(!1),sn=(0,o.A)(an,2),ln=sn[0],dn=sn[1],cn=(0,a.useState)(""),un=(0,o.A)(cn,2),mn=un[0],pn=un[1],gn=(0,a.useState)(null),hn=(0,o.A)(gn,2),fn=hn[0],yn=hn[1],vn=(0,a.useState)(!1),xn=(0,o.A)(vn,2),bn=xn[0],wn=xn[1],kn=(0,a.useState)(!1),An=(0,o.A)(kn,2),jn=An[0],Nn=An[1],Cn=(0,a.useState)(""),Sn=(0,o.A)(Cn,2),En=Sn[0],In=Sn[1],Dn=(0,a.useRef)(null),Pn=(0,a.useRef)(null),Tn=(0,a.useRef)((null===t||void 0===t?void 0:t.category)||""),Rn=(0,a.useRef)(!1),On=(0,a.useState)({top:0,left:0}),Fn=(0,o.A)(On,2),Ln=Fn[0],_n=Fn[1],Un=(0,a.useState)(!1),Mn=(0,o.A)(Un,2),zn=Mn[0],Bn=Mn[1],Wn=null!=ct?null!==dt&&void 0!==dt&&dt:zn,Vn=null!==ct&&void 0!==ct?ct:Bn,Jn=(0,a.useState)(null),qn=(0,o.A)(Jn,2),Hn=qn[0],Gn=qn[1],Kn=(0,a.useState)(!1),Qn=(0,o.A)(Kn,2),Yn=Qn[0],Zn=Qn[1],$n=(0,a.useRef)(null),Xn=null!==lt&&void 0!==lt?lt:$n,er=(0,a.useRef)(null),tr=(0,a.useState)({top:0,right:0}),nr=(0,o.A)(tr,2),rr=nr[0],or=nr[1],ar=(0,s.Zp)(),ir=(0,a.useMemo)(()=>Boolean(Ve&&Je||He&&Ge||Qe&&Ye||$e&&Xe||ie&&se||ze&&Be||Fe&&Ue||Pe&&Te&&Re||yt&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)||te&&oe||rt||at||st||ut||mt),[Ve,Je,He,Ge,Qe,Ye,$e,Xe,ie,se,ze,Be,Fe,Ue,Pe,Te,Re,yt,null===t||void 0===t?void 0:t.id,null===t||void 0===t?void 0:t.isNew,te,oe,rt,at,st,ut,mt]),sr=!Se&&!!t&&!!me&&tt,lr=(0,a.useMemo)(()=>!ir&&Boolean(sr||Ee&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)||Ie&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)||M&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)),[ir,sr,Ee,Ie,M,null===t||void 0===t?void 0:t.id,null===t||void 0===t?void 0:t.isNew]);(0,a.useEffect)(()=>{const e=(null===t||void 0===t?void 0:t.category)||"";Rn.current?e===Tn.current&&(Rn.current=!1):e!==Tn.current&&(Ct(e),Tn.current=e)},[null===t||void 0===t?void 0:t.id,null===t||void 0===t?void 0:t.category]),(0,a.useEffect)(()=>{Ct((null===t||void 0===t?void 0:t.category)||""),Tn.current=(null===t||void 0===t?void 0:t.category)||"",Rn.current=!1,Dt(!1),Nn(!1),In("")},[null===t||void 0===t?void 0:t.id]),(0,a.useEffect)(()=>((0,B.gg)("??? DocumentToolbar MOUNTED"),()=>(0,B.gg)("?? DocumentToolbar UNMOUNTED")),[]);const dr=(0,a.useCallback)(e=>
1{const t=("string"===typeof e?e.trim():"")||Q.cA;Ct(t),t!==Tn.current&&(null===n||void 0===n||n(t),Tn.current=t,Rn.current=!0)},[n]),cr=(0,a.useMemo)(()=>kt(),[kt]),ur=(0,a.useMemo)(()=>{const e=new Set([...S]);return cr.forEach(t=>{"Default"!==t&&e.add(t)}),Array.from(e).sort()},[S,cr]),mr=(0,a.useCallback)(()=>{if(It&&Pn.current){const e=Pn.current.getBoundingClientRect();_n({top:e.bottom+4,left:e.left})}},[It]);(0,a.useEffect)(()=>{if(mr(),It)return window.addEventListener("resize",mr),window.addEventListener("scroll",mr,!0),()=>{window.removeEventListener("resize",mr),window.removeEventListener("scroll",mr,!0)}},[It,mr]),(0,a.useEffect)(()=>{function e(e){Pn.current&&!Pn.current.contains(e.target)&&Dn.current&&!Dn.current.contains(e.target)&&(Dt(!1),Nn(!1),In(""))}if(It)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[It]);const pr=(0,a.useCallback)(()=>{if(Wn&&Xn.current){const e=Xn.current.getBoundingClientRect();or({top:e.bottom+4,right:"undefined"!==typeof window?window.innerWidth-e.right:0})}},[Wn]);(0,a.useEffect)(()=>{if(pr(),Wn)return window.addEventListener("resize",pr),window.addEventListener("scroll",pr,!0),()=>{window.removeEventListener("resize",pr),window.removeEventListener("scroll",pr,!0)}},[Wn,pr]),(0,a.useEffect)(()=>{function e(e){Xn.current&&!Xn.current.contains(e.target)&&er.current&&!er.current.contains(e.target)&&(Vn(!1),Gn(null))}if(Wn)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[Wn]);const gr=async()=>{if(!En.trim()||!z)return;const e=En.trim();In(""),Nn(!1);try{const t=await z(e);if(t){(0,B.gg)("? New workspace created:",t);const e=cr.filter(e=>"Default"!==e).map(e=>{const t=null===O||void 0===O?void 0:O.find(t=>t.name===e);return t?t.id:e}).filter(e=>e&&"Default"!==e&&null!==e&&void 0!==e),n=e.includes(t.id)?e:[...e,t.id];(0,B.gg)("?? Updating document workspaces to include new workspace:",{currentWorkspaces:cr,currentWorkspaceIds:e,newWorkspaceId:t.id,newWorkspaceName:t.name,updatedWorkspaceIds:n}),null===h||void 0===h||h(n),Dt(!1),(0,B.gg)("? Document workspace updated, sidebar will refresh via event")}}catch(t){console.error("Error creating workspace:",t),V.Ay.error("Failed to create workspace. Please try again.")}},hr=()=>{Nn(!1),In("")},fr=(0,H.Nn)(t,{isGlobalView:!0});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("div",{className:"mb-0 pb-0.5 relative z-[40]","data-toolbar":!0,"data-breadcrumb":!0,children:[ht&&Y&&(0,$.jsx)("div",{className:"mb-3",children:(0,$.jsxs)("button",{onClick:Y,className:"flex items-center gap-2 text-base text-gray-600 hover:text-gray-900 transition-colors duration-150",children:[(0,$.jsx)(g.A,{className:"w-5 h-5"}),(0,$.jsx)("span",{children:"Back to all documents"})]})}),(0,$.jsxs)("div",{className:"flex items-center gap-2 ".concat(wt?"justify-start mb-0":"justify-between mb-2"),children:[(0,$.jsxs)("div",{className:"flex items-center gap-2",children:[(0,$.jsx)(K.A,{value:Nt,presets:m,onChange:dr}),(0,$.jsx)("span",{className:"text-gray-400 mx-1 text-sm",children:"/"}),(0,$.jsxs)("div",{className:"relative",children:[(0,$.jsxs)("button",{ref:Pn,onClick:()=>Dt(!It),className:"flex items-center gap-2 px-3 py-1.5 text-sm rounded hover:bg-gray-100 transition-colors duration-150 max-w-xs",children:[(0,$.jsx)("span",{className:"text-gray-700 truncate",children:(()=>{const e=cr.filter(e=>"Default"!==e);return 0===e.length?null!==t&&void 0!==t&&t.isNew?"Select workspace":"Default":1===e.length?e[0]:e.length<=3?e.join(", "):"".concat(e.slice(0,2).join(", ")," +").concat(e.length-2," more")})()}),cr.filter(e=>"Default"!==e).length>1&&(0,$.jsx)("span",{className:"inline-flex items-center justify-center w-5 h-5 text-xs bg-blue-100 text-blue-600 rounded-full flex-shrink-0",children:cr.filter(e=>"Default"!==e).length}),(0,$.jsx)("svg",{className:"w-3 h-3 text-gray-400 transition-transform flex-shrink-0 ".concat(It?"rotate-180":""),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,$.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})]}),It&&"undefined"!==typeof document&&(0,i.createPortal)((0,$.jsx)("div",{ref:Dn,className:"fixed w-72 bg-white border border-gray-200 rounded-md shadow-lg max-h-80 overflow-y-auto",style:{left:"".concat(Ln.left,"px"),top:"".concat(Ln.top,"px"),zIndex:999999,position:"fixed",isolation:"isolate"},children:(0,$.jsxs)("div",{className:"py-1",children:[(0,$.jsx)("div",{className:"px-3 py-2 text-xs font-medium text-gray-500 uppercase tracking-wide",children:"Select Worksp
1aces"}),jn?(0,$.jsxs)("div",{className:"px-3 py-2 border-b border-gray-100",children:[(0,$.jsx)("input",{type:"text",value:En,onChange:e=>In(e.target.value),onKeyDown:e=>{"Enter"===e.key?(e.preventDefault(),gr()):"Escape"===e.key&&hr()},placeholder:"Enter workspace name",autoFocus:!0,className:"w-full px-2 py-1.5 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"}),(0,$.jsxs)("div",{className:"flex items-center gap-2 mt-2",children:[(0,$.jsx)("button",{onClick:gr,disabled:!En.trim(),className:"px-3 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed transition-colors",children:"Create"}),(0,$.jsx)("button",{onClick:hr,className:"px-3 py-1 text-xs text-gray-600 hover:bg-gray-100 rounded transition-colors",children:"Cancel"})]})]}):(0,$.jsxs)("button",{type:"button",onClick:e=>{e.preventDefault(),e.stopPropagation(),(0,B.gg)("??? Create New Workspace button clicked",{hasOnCreateWorkspace:!!z}),z?(e=>{e&&(e.preventDefault(),e.stopPropagation()),(0,B.gg)("?? Starting workspace creation"),Nn(!0),In("")})(e):((0,B.gg)("?? onCreateWorkspace not available"),V.Ay.error("Workspace creation is not available. Please refresh the page."))},onMouseDown:e=>{e.stopPropagation()},className:"w-full text-left px-3 py-2 text-sm flex items-center gap-2 border-b border-gray-100 transition-colors relative z-10 ".concat(z?"text-blue-600 hover:bg-blue-50 active:bg-blue-100 cursor-pointer":"text-gray-400 cursor-not-allowed opacity-50"),style:{pointerEvents:"auto"},disabled:!z,children:[(0,$.jsx)(R.A,{className:"w-4 h-4"}),(0,$.jsx)("span",{children:"Create New Workspace"})]}),ur.map(e=>{const t=cr.includes(e);return(0,$.jsxs)("button",{onClick:()=>(e=>{if(!h)return;let t;cr.includes(e)?(t=cr.filter(t=>t!==e),0===t.length&&(t=["Default"])):t=[...cr.filter(e=>"Default"!==e),e];const n=t.map(e=>{if("Default"===e)return"Default";const t=null===O||void 0===O?void 0:O.find(t=>t.name===e);return t?t.id:e});h(n)})(e),className:"w-full text-left px-3 py-2 text-sm hover:bg-gray-50 flex items-center justify-between",children:[(0,$.jsx)("span",{className:t?"text-blue-700 font-medium":"text-gray-700",children:e}),t&&(0,$.jsx)("svg",{className:"w-4 h-4 text-blue-500",fill:"currentColor",viewBox:"0 0 20 20",children:(0,$.jsx)("path",{fillRule:"evenodd",d:"M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z",clipRule:"evenodd"})})]},e)}),cr.filter(e=>"Default"!==e).length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)("div",{className:"my-1 border-b border-gray-100"}),(0,$.jsx)("button",{onClick:()=>{h&&h(["Default"]),Dt(!1)},className:"w-full text-left px-3 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2",children:"Clear All Workspaces"})]})]})}),document.body)]}),t&&(0,$.jsx)(ee,{currentDoc:t})]}),!wt&&(0,$.jsxs)("div",{ref:e=>{je&&(je.current=e),Ne&&Ne(!!e)},className:"flex items-center gap-2","data-editor-chrome":!0,children:[te&&oe&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)&&(0,$.jsx)(J.A,{documentId:t.id,onVersionRestored:()=>{"undefined"!==typeof window&&window.dispatchEvent(new CustomEvent("documentVersionRestored",{detail:{documentId:t.id}}))}}),Z&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)&&(0,$.jsx)(re,{currentDoc:t,onShare:Z,getEmailPlainText:pt}),null==lt&&(0,$.jsx)("div",{className:"relative",children:(0,$.jsx)("button",{ref:$n,type:"button",onClick:()=>{Vn(e=>!e),Wn&&Gn(null)},className:"btn-shimmer cursor-pointer inline-flex items-center gap-2 px-3 py-2 text-base font-medium text-gray-700 bg-white border border-gray-300 rounded hover:bg-gray-50 transition-colors duration-150 relative",title:"Document abilities",children:(0,$.jsxs)("span",{className:"relative z-10 flex items-center gap-2 pointer-events-none",children:[(0,$.jsx)("span",{children:"Abilities"}),(0,$.jsx)(y.A,{className:"w-5 h-5 text-gray-500 transition-transform ".concat(Wn?"rotate-180":""),"aria-hidden":!0})]})})}),Wn&&"undefined"!==typeof document&&(0,i.createPortal)((0,$.jsxs)("div",{ref:er,className:"fixed w-56 bg-white border border-gray-200 rounded-md shadow-lg py-1 z-[999999]",style:{to
1p:"".concat(rr.top,"px"),right:"".concat(rr.right,"px"),left:"auto"},children:[null===Hn&&(0,$.jsxs)($.Fragment,{children:[!ir&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("button",{type:"button",onClick:()=>{ar("/integrations"),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(l.A,{className:"w-4 h-4 shrink-0"}),"Find new abilities to add"]}),lr&&(0,$.jsx)("div",{className:"my-1 border-t border-gray-100"})]}),Ve&&Je&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Je(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(u.A,{className:"w-4 h-4 shrink-0"}),"Update with AI"]}),ut&&(0,$.jsxs)("button",{type:"button",onClick:()=>{ut(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(_.A,{size:16,className:"shrink-0"}),"Open in ChatGPT"]}),mt&&(0,$.jsxs)("button",{type:"button",onClick:()=>{mt(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(U.A,{size:16}),"Open in Claude"]}),He&&Ge&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Ge(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(x.A,{className:"w-4 h-4 shrink-0"}),"Forms"]}),Qe&&Ye&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Ye(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(j.A,{className:"w-4 h-4 shrink-0"}),"Fill template"]}),$e&&Xe&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Xe(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(I.A,{className:"w-4 h-4 shrink-0"}),"New Env Vault"]}),ie&&se&&(0,$.jsxs)("button",{type:"button",onClick:()=>{se(),Vn(!1),Gn(null)},disabled:de||!t,className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed",children:[(0,$.jsx)(A.A,{className:"w-4 h-4 shrink-0"}),de?"Generating?":"Export as PDF"]}),!Se&&t&&me&&tt&&(0,$.jsxs)("button",{type:"button",onClick:()=>{me(!0),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(k.A,{className:"w-4 h-4 shrink-0"}),"Payment"]}),Ee&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Ee(t.id),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(w.A,{className:"w-4 h-4 shrink-0"}),"Duplicate"]}),Ie&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Ie(t.id),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(p.A,{className:"w-4 h-4 shrink-0"}),"Archive"]}),ze&&Be&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Be(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(T.A,{className:"w-4 h-4 shrink-0"}),"Voice"]}),Fe&&Ue&&(0,$.jsxs)("button",{type:"button",onClick:()=>{Ue(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(b.A,{className:"w-4 h-4 shrink-0"}),"Timer"]}),Pe&&Te&&Re&&(0,$.jsxs)("button",{type:"button",onClick:()=>Gn("signature"),className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between gap-2",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(c.A,{className:"w-4 h-4 shrink-0"}),"Add Signature"]}),(0,$.jsx)(v.A,{className:"w-4 h-4 shrink-0 text-gray-400"})]}),yt&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)&&(0,$.jsx)($.Fragment,{children:null!==t&&void 0!==t&&t.locked?(0,$.jsxs)("button",{type:"button",onClick:()=>{dn(!0),pn(""),yn(null),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(d.A,{className:"w-4 h-4 shrink-0"}),"Unlock document"]}):(0,$.jsxs)("button",{type:"button",onClick:()=>{Yt(!0),en(null),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center gap-2",children:[(0,$.jsx)(D.A,{className:"w-4 h-4 shrink-0"}),"Lock document"]})}),(te&&oe||rt||at||st)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)("div",{className:"my-1 border-t border-gray-100"}),te&&oe&&(0,$.jsxs)("button",{type:"button",onClick:()=>{ar("/integrations"),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between gap-2",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(C.A,{className:"w-4 h-4 shrink-0"}),"Version Control"]}),(0,$.jsx)("span",{className:"text-xs font-medium text-green-600",children:"ON"})]}),rt&&(0,$.jsxs)("button",{type:"button",onClick:()=>{ar("/integrations"),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between gap-2",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(L.A,{className:"w-4 h-4 shrink-0"}),"Auto Title"]}),(0,$.jsx)("span",{className:"text-xs font-medium text-green-600",children:"ON"})]}),at&&(0,$.jsxs)("button",{type:"button",onClick:()=>{ar("/integrations"),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between gap-2",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(N.A,{className:"w-4 h-4 shrink-0"}),"Auto Category"]}),(0,$.jsx)("span",{className:"text-xs font-medium text-green-600",children:"ON"})]}),st&&(0,$.jsxs)("button",{type:"button",onClick:()=>{ar("/integrations"),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between gap-2",children:[(0,$.jsxs)("span",{className:"flex items-center gap-2",children:[(0,$.jsx)(E.A,{className:"w-4 h-4 shrink-0"}),"Pexels Images"]}),(0,$.jsx)("span",{className:"text-xs font-medium text-green-600",children:"ON"})]})]}),M&&(null===t||void 0===t?void 0:t.id)&&!(null!==t&&void 0!==t&&t.isNew)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)("div",{className:"my-1 border-t border-gray-100"}),(0,$.jsxs)("button",{type:"button",onClick:()=>{Ut(""),Wt(null),Ot(!0),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2",children:[(0,$.jsx)(F.A,{className:"w-4 h-4 shrink-0"}),"Delete"]})]})]}),"signature"===Hn&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)("button",{type:"button",onClick:()=>Gn(null),className:"w-full text-left px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 flex items-center gap-2 border-b border-gray-100",children:"? Back"}),(0,$.jsxs)("button",{type:"button",onClick:()=>Gn("field"),className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 flex items-center justify-between gap-2",children:[(0,$.jsx)("span",{children:"Add field"}),(0,$.jsx)(v.A,{className:"w-4 h-4 shrink-0 text-gray-400"})]}),(0,$.jsx)("button",{type:"button",onClick:()=>{null===Re||void 0===Re||Re(),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50",children:"Add signature pad"})]}),"field"===Hn&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)("button",{type:"button",onClick:()=>Gn("signature"),className:"w-full text-left px-3 py-2 text-sm text-gray-600 hover:bg-gray-50 flex items-center gap-2 border-b border-gray-100",children:"? Back"}),W.bh.map(e=>(0,$.jsx)("button",{type:"button",onClick:()=>
1{null===Te||void 0===Te||Te(e),Vn(!1),Gn(null)},className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 capitalize",children:e},e))]})]}),document.body)]})]})]}),!Se&&t&&me&&ue&&"undefined"!==typeof document&&(0,i.createPortal)(((e,n)=>{const r=null===Xn||void 0===Xn||null===(e=Xn.current)||void 0===e||null===(n=e.getBoundingClientRect)||void 0===n?void 0:n.call(e);return(0,$.jsxs)("div",{className:"fixed inset-0 z-[9998]",style:{pointerEvents:"none"},children:[(0,$.jsx)("div",{className:"fixed inset-0 z-[9998] bg-black/20",style:{pointerEvents:"auto"},"aria-hidden":!0,onClick:()=>me(!1)}),(0,$.jsxs)("div",{className:"fixed z-[9999] w-80 bg-white border border-gray-200 rounded-lg shadow-lg p-4",style:{pointerEvents:"auto",top:r?r.bottom+8:0,right:r&&"undefined"!==typeof window?window.innerWidth-r.right:0},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)("h3",{className:"text-sm font-medium text-gray-900 mb-3",children:"Payment"}),(0,$.jsxs)("div",{className:"space-y-3",children:[(0,$.jsxs)("div",{className:"flex items-center justify-between",children:[(0,$.jsx)("label",{className:"text-sm text-gray-700",children:"Enable payment"}),(0,$.jsx)("button",{type:"button",role:"switch","aria-checked":!(null===t||void 0===t||!t.paymentEnabled),disabled:ge,onClick:e=>{e.preventDefault(),e.stopPropagation(),!ge&&null!==t&&void 0!==t&&t.id&&(null===he||void 0===he||he(t.id,{paymentEnabled:!(null!==t&&void 0!==t&&t.paymentEnabled)}))},className:"relative inline-flex h-6 w-11 flex-shrink-0 rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 ".concat(ge?"cursor-not-allowed opacity-70":"cursor-pointer"," ").concat(null!==t&&void 0!==t&&t.paymentEnabled?"bg-blue-600":"bg-gray-200"),children:(0,$.jsx)("span",{className:"pointer-events-none inline-block h-5 w-5 transform rounded-full bg-white shadow ring-0 transition-transform ".concat(null!==t&&void 0!==t&&t.paymentEnabled?"translate-x-5":"translate-x-1")})})]}),(null===t||void 0===t?void 0:t.paymentEnabled)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("div",{children:[(0,$.jsx)("label",{className:"text-sm text-gray-700 block mb-1",children:"Description on checkout"}),(0,$.jsx)("input",{type:"text",maxLength:200,placeholder:"Document payment",defaultValue:(null===t||void 0===t?void 0:t.paymentProductName)||"",onBlur:e=>{const n=e.target.value.trim();n!==((null===t||void 0===t?void 0:t.paymentProductName)||"")&&(null===he||void 0===he||he(t.id,{paymentProductName:n||null}))},className:"w-full rounded border border-gray-300 px-2 py-1.5 text-sm"})]}),Array.isArray(null===t||void 0===t?void 0:t.paymentLinks)&&t.paymentLinks.length>1?(0,$.jsxs)("div",{children:[(0,$.jsx)("label",{className:"text-sm text-gray-700 block mb-1",children:"Payment links"}),(0,$.jsx)("ul",{className:"rounded-md border border-gray-200 bg-gray-50 divide-y divide-gray-200 text-sm",children:t.paymentLinks.map((e,t)=>(0,$.jsxs)("li",{className:"flex items-center justify-between px-2 py-1.5",children:[(0,$.jsx)("span",{className:"text-gray-600 truncate mr-2",children:e.productName||"Payment ".concat(t+1)}),(0,$.jsx)("span",{className:"text-gray-900 font-medium whitespace-nowrap",children:null!=e.amountCents?"$".concat((e.amountCents/100).toFixed(2)):"?"})]},e.id||t))}),(0,$.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"This document has multiple payment links. Edit each amount by clicking its button in the document."})]}):(0,$.jsxs)("div",{children:[(0,$.jsx)("label",{className:"text-sm text-gray-700 block mb-1",children:"One-time amount"}),(0,$.jsx)("input",{type:"number",min:"0",step:"0.01",placeholder:"0.00",value:null!==ye&&void 0!==ye?ye:null!=(null===t||void 0===t?void 0:t.paymentAmountCents)?(t.paymentAmountCents/100).toFixed(2):"",onFocus:()=>{const e=null!=(null===t||void 0===t?void 0:t.paymentAmountCents)?(t.paymentAmountCents/100).toFixed(2):"";null===ve||void 0===ve||ve(e)},onChange:e=>null===ve||void 0===ve?void 0:ve(e.target.value),onBlur:()=>{const e=ye;if(null===ve||void 0===ve||ve(null),""===e||null===e)return void(null===he||void 0===he||he(t.id,{paymentAmountCents:null}));const n=parseFloat(e);
1if(!Number.isNaN(n)&&n>=0){const e=Math.round(100*n);null===he||void 0===he||he(t.id,{paymentAmountCents:e})}},className:"w-full rounded border border-gray-300 px-2 py-1.5 text-sm"}),(0,$.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"Leave empty when this document only needs a subscription."})]}),(0,$.jsxs)("div",{className:"rounded-md border border-gray-200 bg-gray-50 p-3 space-y-3",children:[(0,$.jsxs)("label",{className:"flex items-start gap-2 cursor-pointer",children:[(0,$.jsx)("input",{type:"checkbox",checked:null!==ke&&void 0!==ke?ke:!(null===t||void 0===t||!t.paymentSubscriptionEnabled),onChange:e=>{null===he||void 0===he||he(t.id,{paymentSubscriptionEnabled:e.target.checked,paymentSubscriptionInterval:"month"})},className:"mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,$.jsxs)("span",{className:"text-sm text-gray-700 leading-tight",children:["Add monthly subscription",(0,$.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5",children:"Collect a recurring line for hosting, servers, or Based."})]})]}),(null!==ke&&void 0!==ke?ke:!(null===t||void 0===t||!t.paymentSubscriptionEnabled))&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)("div",{children:[(0,$.jsx)("label",{className:"text-sm text-gray-700 block mb-1",children:"Subscription description"}),(0,$.jsx)("input",{type:"text",maxLength:200,placeholder:"Monthly hosting",defaultValue:(null===t||void 0===t?void 0:t.paymentSubscriptionProductName)||"",onBlur:e=>{const n=e.target.value.trim();n!==((null===t||void 0===t?void 0:t.paymentSubscriptionProductName)||"")&&(null===he||void 0===he||he(t.id,{paymentSubscriptionProductName:n||null}))},className:"w-full rounded border border-gray-300 px-2 py-1.5 text-sm"})]}),(0,$.jsxs)("div",{children:[(0,$.jsx)("label",{className:"text-sm text-gray-700 block mb-1",children:"Monthly amount"}),(0,$.jsx)("input",{type:"number",min:"0",step:"0.01",placeholder:"0.00",value:null!==be&&void 0!==be?be:null!=(null===t||void 0===t?void 0:t.paymentSubscriptionAmountCents)?(t.paymentSubscriptionAmountCents/100).toFixed(2):"",onFocus:()=>{const e=null!=(null===t||void 0===t?void 0:t.paymentSubscriptionAmountCents)?(t.paymentSubscriptionAmountCents/100).toFixed(2):"";null===we||void 0===we||we(e)},onChange:e=>null===we||void 0===we?void 0:we(e.target.value),onBlur:()=>{const e=be;if(null===we||void 0===we||we(null),""===e||null===e)return void(null===he||void 0===he||he(t.id,{paymentSubscriptionAmountCents:null}));const n=parseFloat(e);if(!Number.isNaN(n)&&n>=0){const e=Math.round(100*n);null===he||void 0===he||he(t.id,{paymentSubscriptionAmountCents:e})}},className:"w-full rounded border border-gray-300 px-2 py-1.5 text-sm"})]})]})]}),Pe&&(0,$.jsxs)("label",{className:"flex items-start gap-2 cursor-pointer",children:[(0,$.jsx)("input",{type:"checkbox",checked:!(null===t||void 0===t||!t.paymentRevealAfterSignature),onChange:e=>{null===he||void 0===he||he(t.id,{paymentRevealAfterSignature:e.target.checked})},className:"mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,$.jsxs)("span",{className:"text-sm text-gray-700 leading-tight",children:["Reveal after signature",(0,$.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5",children:"Payment appears only after signing is complete"})]})]}),(0,$.jsxs)("label",{className:"flex items-start gap-2 cursor-pointer",children:[(0,$.jsx)("input",{type:"checkbox",checked:!(null===t||void 0===t||!t.paymentReminderEnabled),onChange:e=>{null===he||void 0===he||he(t.id,{paymentReminderEnabled:e.target.checked})},className:"mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,$.jsxs)("span",{className:"text-sm text-gray-700 leading-tight",children:["Send payment reminders",(0,$.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5",children:"Email the signer if they don't pay within 15 minutes"})]})]}),(0,$.jsx)("button",{type:"button",onClick:e=>{e.preventDefault(),e.stopPropagation(),null===Ae||void 0===Ae||Ae()},className:"w-full mt-2 px-3 py-2 text-sm font-medium rounded-md border border-gray-300 bg-white hover:bg-gray-50 text-gray-700",children:"Place Pay Button"})]})]})]})]})})(),document.body),Fe&&_e&&Yn&&"undefined"!==typeof document&&(0,i.createPortal)(((e,t)=>{const n=null===Xn||void 0===Xn||null===(e=Xn.current)||void 0===e||null===(t=e.getBoundingClientRect)||void 0===t?void 0:t.call(e);return(0,$.jsxs)("div",{className:"fixed inset-0 z-[9998]",style:{pointerEvents:"none"},children:[(0,$.jsx)("div",{className:"fixed inset-0 z-[9998] bg-black/20",style:{pointerEvents:"auto"},"aria-hidden":!0,onClick:()=>Zn(!1)}),(0,$.jsx)("div",{className:"fixed z-[9999] min-w-[280px] bg-white border border-gray-200 rounded-lg shadow-lg p-3",style:{pointerEvents:"auto",top:n?n.bottom+8:0,right:n&&"undefined"!==typeof window?window.innerWidth-n.right:0},onClick:e=>e.stopPropagation(),children:_e})]})})(),document.body),(0,$.jsx)(q.R,{isOpen:Rt,title:"Delete Document",message:null!==t&&void 0!==t&&t.locked?'This document is locked. Type "unlock document" below, then click "Unlock and delete" to permanently delete "'.concat((null===t||void 0===t?void 0:t.t
1itle)||"this document",'".'):"envVault"===fr.kind?'This secrets document cannot be deleted accidentally. Type "'.concat(H.ZE,'" below, then click Delete to permanently delete "').concat((null===t||void 0===t?void 0:t.title)||"this document",'".'):'Are you sure you want to permanently delete "'.concat((null===t||void 0===t?void 0:t.title)||"this document",'"? This action cannot be undone.'),onConfirm:async()=>{if(M&&null!==t&&void 0!==t&&t.id){Wt(null),Ht(!0);try{const e=(0,H.Gp)(t,_t,{isGlobalView:!0});await M(t.id,e),Ot(!1),Ut(""),Wt(null)}catch(e){const t=(null===e||void 0===e?void 0:e.message)||"Failed to delete document.";(0,H.LD)(t)?Wt(t):(V.Ay.error(t),Ot(!1),Ut(""))}finally{Ht(!1)}}},onCancel:()=>{Ot(!1),Ut(""),Wt(null)},confirmText:null!==t&&void 0!==t&&t.locked?"Unlock and delete":"Delete",showUnlockPhraseInput:fr.showInput,unlockPhrase:_t,onUnlockPhraseChange:Ut,unlockPhraseError:Bt,unlockPhraseLabel:fr.label,unlockPhrasePlaceholder:fr.placeholder,requiredPhrase:fr.requiredPhrase,isConfirming:qt}),Qt&&(0,$.jsx)(q.Q,{children:(0,$.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50",children:(0,$.jsxs)("div",{className:"bg-white rounded-lg shadow-lg p-6 w-full max-w-md",children:[(0,$.jsx)("h3",{className:"text-lg font-medium mb-2",children:"Lock document"}),(0,$.jsx)("p",{className:"text-gray-600 mb-4",children:'This document will be locked preventing it from being easily deleted. To delete it later, you will use the phrase "unlock document" to unlock and delete.'}),Xt&&(0,$.jsx)("p",{className:"text-sm text-red-600 mb-4",children:Xt}),(0,$.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,$.jsx)("button",{type:"button",onClick:()=>{Yt(!1),en(null)},className:"px-4 py-2 text-sm text-gray-700 bg-gray-100 hover:bg-gray-200 rounded transition-colors",children:"Cancel"}),(0,$.jsx)(G.A,{type:"button",onClick:async()=>{if(vt&&null!==t&&void 0!==t&&t.id){en(null),on(!0);try{await vt(t.id),V.Ay.success("Document locked."),Yt(!1)}catch(e){en((null===e||void 0===e?void 0:e.message)||"Failed to lock document.")}finally{on(!1)}}},disabled:rn,size:"md",className:"px-4 py-2 text-sm rounded transition-colors disabled:opacity-50",children:rn?"Locking?":"Lock document"})]})]})})}),ln&&(0,$.jsx)(q.Q,{children:(0,$.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50",children:(0,$.jsxs)("div",{className:"bg-white rounded-lg shadow-lg p-6 w-full max-w-md",children:[(0,$.jsx)("h3",{className:"text-lg font-medium mb-2",children:"Unlock document"}),(0,$.jsx)("p",{className:"text-gray-600 mb-4",children:'Type "unlock document" below to unlock this document. You can then edit and delete it without entering the phrase again.'}),(0,$.jsxs)("div",{className:"mb-4",children:[(0,$.jsx)("label",{htmlFor:"unlock-phrase-unlock",className:"block text-sm font-medium text-gray-700 mb-1",children:'Type "unlock document"'}),(0,$.jsx)("input",{id:"unlock-phrase-unlock",type:"text",value:mn,onChange:e=>pn(e.target.value),placeholder:"unlock document",className:"block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 sm:text-sm",autoComplete:"off"}),fn&&(0,$.jsx)("p",{className:"mt-1 text-sm text-red-600",children:fn})]}),(0,$.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,$.jsx)("button",{type:"button",onClick:()=>{dn(!1),pn(""),yn(null)},className:"px-4 py-2 text-sm text-gray-700 bg-gray-100 hover:bg-gray-200 rounded transition-colors",children:"Cancel"}),(0,$.jsx)(G.A,{type:"button",onClick:async()=>{if(xt&&null!==t&&void 0!==t&&t.id){yn(null),wn(!0);try{await xt(t.id,mn),V.Ay.success("Document unlocked."),dn(!1),pn(""),yn(null)}catch(e){yn((null===e||void 0===e?void 0:e.message)||"Failed to unlock document.")}finally{wn(!1)}}},disabled:bn||!(null!==mn&&void 0!==mn&&mn.trim()),size:"md",className:"px-4 py-2 text-sm rounded transition-colors disabled:opacity-50",children:bn?"Unlocking?":"Unlock"})]})]})})})]})}},92829(e,t,n){n.d(t,{A:()=>v});var r=n(5544),o=n(65043),a=n(97950),i=n(36210),s=n(92382),l=n(75088),d=n(94805),c=n(40614),u=n(66630),m=n(18303),p=n(24489),g=n(1862),h=n(92339),f=n(60678),y=n(70579);function v(e){let t=e.documentId,n=e.onVersionRestored;const v=(0,o.useState)(!1),x=(0,r.A)(v,2),b=x[0],w=x[1],k=(0,o.useState)([]),A=(0,r.A)(k,2),j=A[0],N=A[1],C=(0,o.useState)(!1),S=(0,r.A)(C,2),E=S[0],I=S[1],D=(0,o.useState)(!1),P=(0,r.A)(D,2),T=P[0],R=P[1],O=(0,o.useState)(!1),F=(0,r.A)(O,2),L=F[0],_=F[1],U=(0,o.useState)(!1),M=(0,r.A)(U,2),z=M[0],B=M[1],W=(0,o.useState)({top:0,left:0,maxHeight:400}),V=(0,r.A)(W,2),J=V[0],q=V[1],H=(0,o.useRef)(null),G=(0,o.useRef)(null),K=(0,o.useRef)(null),Q=16,Y=()=>{if(b&&H.current&&"undefined"!==typeof window){const e=H.current.getBoundingClientRect(),t=window.innerHeight,n=window.innerWidth,r=t-e.bottom-Q,o=e.top-Q;let a,i;r>=o&&r>0?(a=e.bottom+4,i=Math.min(400,Math.max(120,r))):o>0?(i=Math.min(400,Math.max(120,o)),a=e.top-4-i):(a=e.bottom+4,i=Math.max(120,Math.min(400,r)));let s=e.right-384;s<Q&&(s=Q),s+384>n-Q&&(s=n-384-Q),q({top:a,left:s,maxHeight:i})}};(0,o.useEffect)(()=>
1{if(Y(),b)return window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0)}},[b]);const Z=(0,o.useCallback)(async()=>{if(t){K.current=null,I(!0);try{const e=await(0,m.x1)(t,{limit:50}),n=e.versions,r=e.hasMore,o=e.lastSnapshot;N(n),_(r),K.current=o,(0,g.gg)("\ud83d\udcda Loaded ".concat(n.length," versions"))}catch(e){console.error("\u274c Error loading versions:",e),h.Ay.error("Failed to load document versions")}finally{I(!1)}}},[t]);(0,o.useEffect)(()=>{b&&t&&Z()},[b,t,Z]),(0,o.useEffect)(()=>{if(!t)return;const e=e=>{var n;(null===e||void 0===e||null===(n=e.detail)||void 0===n?void 0:n.documentId)===t&&b&&Z()};return window.addEventListener(p.Xy,e),()=>window.removeEventListener(p.Xy,e)},[t,b,Z]);(0,o.useEffect)(()=>{function e(e){H.current&&!H.current.contains(e.target)&&G.current&&!G.current.contains(e.target)&&w(!1)}if(b)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[b]);const $=e=>{if(!e)return"Unknown date";try{return e.toDate?(0,f.x$)(e.toDate()):e instanceof Date?(0,f.x$)(e):"string"===typeof e?(0,f.x$)(new Date(e)):"Unknown date"}catch(t){return"Unknown date"}};return t?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsxs)("button",{type:"button",ref:H,onClick:()=>w(!b),className:"cursor-pointer flex items-center gap-2 px-3 py-1.5 text-sm text-gray-700 hover:bg-gray-100 rounded transition-colors duration-150",title:"View document versions",children:[(0,y.jsx)(l.A,{className:"w-4 h-4 pointer-events-none","aria-hidden":!0}),(0,y.jsx)("span",{className:"pointer-events-none",children:"Versions"}),(0,y.jsx)(s.A,{className:"w-3 h-3 pointer-events-none transition-transform ".concat(b?"rotate-180":""),"aria-hidden":!0})]}),b&&"undefined"!==typeof document&&(0,a.createPortal)((0,y.jsxs)("div",{ref:G,className:"fixed w-96 bg-white border border-gray-200 rounded-md shadow-lg flex flex-col z-[999999]",style:{left:"".concat(J.left,"px"),top:"".concat(J.top,"px"),maxHeight:"".concat(J.maxHeight,"px"),position:"fixed",isolation:"isolate"},children:[(0,y.jsxs)("div",{className:"flex items-center justify-between p-4 pb-0 flex-shrink-0",children:[(0,y.jsx)("h3",{className:"text-sm font-semibold text-gray-900",children:"Document Versions"}),(0,y.jsx)("button",{onClick:()=>w(!1),className:"text-gray-400 hover:text-gray-600",children:(0,y.jsx)(c.A,{className:"w-4 h-4"})})]}),(0,y.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto p-4 pt-3",children:E?(0,y.jsxs)("div",{className:"text-center py-8 text-gray-500",children:[(0,y.jsx)(u.y$,{size:"md",className:"text-gray-400 mx-auto mb-2"}),(0,y.jsx)("p",{className:"text-sm",children:"Loading versions..."})]}):0===j.length?(0,y.jsxs)("div",{className:"text-center py-8 text-gray-500",children:[(0,y.jsx)(l.A,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),(0,y.jsx)("p",{className:"text-sm",children:"No versions found"}),(0,y.jsx)("p",{className:"text-xs mt-1",children:"Versions are created automatically when you save"})]}):(0,y.jsxs)("div",{className:"space-y-2",children:[j.map(e=>(0,y.jsx)("div",{className:"p-3 rounded-lg border transition-colors ".concat(e.isCurrent?"border-blue-300 bg-blue-50":"border-gray-200 hover:border-gray-300 hover:bg-gray-50"),children:(0,y.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,y.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,y.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,y.jsxs)("span",{className:"text-xs font-medium text-gray-600",children:["Version ",e.versionNumber||"?"]}),e.isCurrent&&(0,y.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700",children:[(0,y.jsx)(i.A,{className:"w-3 h-3"}),"Current"]})]}),(0,y.jsx)("p",{className:"text-xs text-gray-500",children:$(e.createdAt)}),e.description&&(0,y.jsx)("p",{className:"text-xs text-gray-500 italic mt-1",children:e.description})]}),!e.isCurrent&&(0,y.jsxs)("button",{onClick:()=>(async e=>{if(t&&e){B(!0);try{await(0,m.gP)(t,e),(0,g.gg)("\u2705 Restored version ".concat(e)),h.Ay.success("Version restored successfully"),w(!1),n&&n()}catch(r){console.error("\u274c Error restoring version:",r),h.Ay.error("Failed to restore version")}finally{B(!1)}}})(e.id),disabled:z,className:"flex items-center gap-1 px-2 py-1 text-xs text-blue-600 hover:bg-blue-100 rounded transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Restore this version",children:[(0,y.jsx)(d.A,{className:"w-3 h-3"}),(0,y.jsx)("span",{children:"Restore"})]})]})},e.id)),L&&(0,y.jsx)("div",{className:"pt-1 flex justify-center",children:(0,y.jsx)("button",{type:"button",onClick:async()=>
1{if(t&&K.current&&!T){R(!0);try{const e=await(0,m.x1)(t,{limit:50,startAfterSnapshot:K.current}),n=e.versions,r=e.hasMore,o=e.lastSnapshot;N(e=>[...e,...n]),_(r),K.current=o,(0,g.gg)("\ud83d\udcda Loaded ".concat(n.length," more versions"))}catch(e){console.error("\u274c Error loading more versions:",e),h.Ay.error("Failed to load older versions")}finally{R(!1)}}},disabled:T,className:"text-sm text-blue-600 hover:text-blue-800 hover:bg-blue-50 px-3 py-2 rounded-md transition-colors disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center gap-2",children:T?(0,y.jsxs)(y.Fragment,{children:[(0,y.jsx)(u.y$,{size:"sm",className:"text-blue-600"}),(0,y.jsx)("span",{children:"Loading\u2026"})]}):(0,y.jsx)("span",{children:"See more"})})})]})})]}),document.body)]}):null}},95739(e,t,n){n.r(t),n.d(t,{default:()=>Ai});var r=n(53986),o=n(89379),a=n(5544),i=n(65043),s=n(97950),l=n(55731),d=n(36210),c=n(40614),u=n(5379),m=n(65505),p=n(9855),g=n(16784),h=n(98142),f=n(14939),y=n(92382),v=n(72105),x=n(71360),b=n(65727),w=n(72313),k=n(7118),A=n(38326),j=n(50516),N=n(7921),C=n(84105),S=n(2284),E=n(30380),I=n(16567),D=n(33908),P=n(22024),T=n(63944),R=n(41680),O=n(14918),F=n(21531),L=n(70764),_=n(39292),U=n(23658),M=n(42983),z=n(47874),B=n(55472),W=n(1862);const V=async(e,t)=>{if(!e||!t||!t.id)return!1;try{const n=(0,B.aU)(),r=(0,B.rJ)(n,"favorites"),o=(0,B.P)(r,(0,B._M)("userId","==",e),(0,B._M)("documentId","==",t.id));return(await(0,B.GG)(o)).empty?(await(0,B.gS)(r,{userId:e,documentId:t.id,title:t.title||t.fileName||"Untitled Document",category:t.category||"Uncategorized",createdAt:(0,B.O5)()}),(0,W.gg)("Document added to favorites"),!0):((0,W.gg)("Document is already a favorite"),!0)}catch(n){return console.error("Error adding favorite:",n),!1}},J=async(e,t)=>{if(!e||!t)return!1;try{const n=(0,B.aU)(),r=(0,B.rJ)(n,"favorites"),o=(0,B.P)(r,(0,B._M)("userId","==",e),(0,B._M)("documentId","==",t)),a=await(0,B.GG)(o);if(a.empty)return(0,W.gg)("Document is not a favorite"),!1;const i=[];return a.forEach(e=>{i.push((0,B.kd)(e.ref))}),await Promise.all(i),(0,W.gg)("Document removed from favorites"),!0}catch(n){return console.error("Error removing favorite:",n),!1}},q=e=>{const t=(0,i.useState)([]),n=(0,a.A)(t,2),r=n[0],o=n[1],s=(0,i.useState)(!0),l=(0,a.A)(s,2),d=l[0],c=l[1],u=(0,i.useState)(null),m=(0,a.A)(u,2),p=m[0],g=m[1],h=async()=>{if(!e)return o([]),void c(!1);try{c(!0);const t=(0,B.aU)(),n=(0,B.rJ)(t,"favorites"),r=(0,B.P)(n,(0,B._M)("userId","==",e)),a=await(0,B.GG)(r),i=[];a.forEach(e=>{i.push({id:e.id,documentId:e.data().documentId,title:e.data().title,category:e.data().category,createdAt:e.data().createdAt})}),o(i)}catch(t){console.error("Error loading favorites:",t),g(t.message)}finally{c(!1)}};(0,i.useEffect)(()=>{h()},[e]);return{favorites:r,loading:d,error:p,addFavorite:async t=>{const n=await V(e,t);return n&&h(),n},removeFavorite:async t=>{const n=await J(e,t);return n&&h(),n},isFavorite:e=>!!r&&r.some(t=>t.documentId===e),refreshFavorites:h}};var H=n(48749),G=n(96822),K=n(18303),Q=n(27810),Y=n(96060),Z=n(5237),$=n(12947),X=n(60626),ee=n(24489);function te(e){return"invalid-argument"===(null===e||void 0===e?void 0:e.code)&&"string"===typeof(null===e||void 0===e?void 0:e.message)&&/cannot be written because its size|exceeds the maximum allowed size of 1,048,576/.test(e.message)}const ne=new class{constructor(){this.encryptionService=Q.E}validateBeforeSave(e){if("pdf"===(null===e||void 0===e?void 0:e.viewerMode))return{willBeModified:!1};const t=(null===e||void 0===e?void 0:e.editorJson)||e;return t?(0,Z.s)(t):{willBeModified:!1}}async saveDocument(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=n.html,o=n.title,a=n.isUpdate,i=void 0!==a&&a,s=n.userId,l=n.workspaceIds,d=n.currentDoc,c=n.originalDoc,u=n.getWorkspaceIds,m=n.getOrCreateDefaultWorkspace,p=n.defaultWorkspaceId,g=n.organizationId,h=n.versionControlEnabled,f=void 0!==h&&h,y=n.isManualSave,v=void 0!==y&&y;if(!e)throw new Error("Document ID is required");if(!s)throw new Error("User ID is required");if((0,W.gg)("\ud83d\udcbe DocumentSaveService.saveDocument called:",{documentId:e,isUpdate:i,isEncrypted:null===t||void 0===t?void 0:t.isEncrypted,hasTitle:!!o,hasHtml:!!r}),!n.skipValidation){const e=this.validateBeforeSave(t);if(e.willBeModified){const t=new Error(e.warning||"Document structure will be modified during save");throw t.name="ValidationWarning",t.validation=e,t}}const x=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.find(e=>void 0!==e&&null!==e)};let b=l;if(!b||0===b.length)if(u){const e=(null===t||void 0===t?void 0:t.workspaceIds)||(null===d||void 0===d?void 0:d.workspaceIds)||(null===c||void 0===c?void 0:c.workspaceIds);b=await u(e)}else{const e=m?await m(s,g):null,t=p||(null===e||void 0===e?void 0:e.workspaceId)||null;b=t?[t]:[]}Array.isArray(b)||(b=b?[b]:[]);const w=b.length>0?b[0]:null,k=x(null===t||void 0===t?void 0:t.category,null===d||void 0===d?void 0:d.category,null===c||void 0===c?void 0:c.category),A=x(null===t||void 0===t?void 0:t.folderId,null===d||void 0===d?void 0:d.folderId,null===c||void 0===c?void 0:c.folderId),j="string"===typeof A&&A.trim()?A.trim():null,N=/^new_|^temp_/.test(String(e));return Boolean(i&&!N)?await this._updateDocument(e,t,{html:r,title:o,userId:s,workspaceIds:b,finalWorkspaceId:w,categoryToSave:k,folderIdToSave:j,currentDoc:d,originalDoc:c,versionControlEnabled:f,organizationId:g,isManualSave:v}):await this._createDocument(e,t,{html:r,title:o,userId:s,workspaceIds:b,finalWorkspaceId:w,categoryToSave:k,folderIdToSave:j,currentDoc:d,versionControlEnabled:f,organizationId:g})}
1async _isVersionControlActiveForSave(e,t){return e?(0,ee.DQ)({organizationId:e}):Boolean(t)}async _createDocument(e,t,r){const a=r.html,i=r.title,s=r.userId,l=r.workspaceIds,d=r.finalWorkspaceId,c=r.categoryToSave,u=r.folderIdToSave,m=void 0===u?null:u,p=r.currentDoc,g=r.versionControlEnabled,h=void 0!==g&&g,f=r.organizationId;if(!("pdf"===(null===t||void 0===t?void 0:t.viewerMode)&&((null===t||void 0===t?void 0:t.url)||(null===t||void 0===t?void 0:t.previewUrl))&&"string"===typeof(null===t||void 0===t?void 0:t.textContent)&&t.textContent.trim().length>0)){const e=!i||"string"===typeof i&&"Untitled Document"===i.trim(),t=(a||"").replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();if(e&&(!t||"Untitled Document"===t)){const e=new Error("Add a title or content to save");throw e.name="ValidationWarning",e}}const y="pdf"===(null===t||void 0===t?void 0:t.viewerMode)?{viewerMode:"pdf",url:t.url||t.previewUrl||null,previewUrl:t.previewUrl||t.url||null,fileName:t.fileName||i||"document.pdf",fileType:t.fileType||"application/pdf"}:{};let v;(0,W.gg)("\ud83d\udcdd Creating new document");const x=(null===t||void 0===t?void 0:t.isEncrypted)&&!(null!==t&&void 0!==t&&t.encryptedResult)&&!(null!==t&&void 0!==t&&t.userEncryptedResult),b=(null===t||void 0===t?void 0:t.isEncrypted)&&((null===t||void 0===t?void 0:t.encryptedResult)||(null===t||void 0===t?void 0:t.userEncryptedResult));if(b||x)if((0,W.gg)("\ud83d\udd12 Creating encrypted document",{needsEncryption:x,hasEncryption:b,hasEncryptedResult:!!t.encryptedResult,hasUserEncrypted:!!t.userEncryptedResult,encryptionMethod:t.encryptionMethod}),t.encryptedResult&&"dual"!==t.encryptionMethod){(0,W.gg)("\ud83d\udd04 Converting legacy encryption to dual encryption");try{const e=await(0,Y.k5)(s),n=await(0,Y.PV)(t.encryptedResult,e);if(!n)throw new Error("Failed to decrypt legacy content");{var w;const e=JSON.parse(n),r=(null===t||void 0===t?void 0:t.editorJson)||e.editorJson||t,u=(0,o.A)((0,o.A)({},e),{},{title:t.title||i||e.title||"Encrypted Document",editorJson:r,editorHtml:a||e.editorHtml,textContent:(a||"").replace(/<[^>]*>/g,"")||e.textContent,category:c,workspace:t.workspace||(null===p||void 0===p?void 0:p.workspace)||"Default",fileName:t.title||i||e.title||"Encrypted Document",fileType:"text/plain"}),m=await this.encryptionService.encryptDocumentForPersist(u,{actingUserId:s,ownerUserId:t.userId||(null===p||void 0===p?void 0:p.userId)||s,workspaceIds:l,existingDoc:t||p||{}});v=(0,o.A)((0,o.A)({},m),{},{title:t.title||i||"Encrypted Document",textContent:"[Encrypted Content]",category:c,workspace:t.workspace||(null===p||void 0===p?void 0:p.workspace)||"Default",userId:t.userId||s,workspaceId:d,status:"completed",fileType:"text/plain",fileSize:0},(null===(w=t.documentImageUrls)||void 0===w?void 0:w.length)>0&&{documentImageUrls:t.documentImageUrls})}}catch(R){var k;console.error("\u274c Failed to convert legacy encryption:",R),v=(0,o.A)({encryptedResult:t.encryptedResult,isEncrypted:!0,encryptionMethod:"legacy",title:t.title||i||"Encrypted Document",textContent:"[Encrypted Content]",category:c,workspace:t.workspace||(null===p||void 0===p?void 0:p.workspace)||"Default",workspaceIds:l,userId:s,workspaceId:d,status:"completed",fileType:"text/plain",fileSize:0},(null===(k=t.documentImageUrls)||void 0===k?void 0:k.length)>0&&{documentImageUrls:t.documentImageUrls})}}else if(t.userEncryptedResult&&"dual"===t.encryptionMethod){var A;(0,W.gg)("\u2705 Document already has dual encryption"),v=(0,o.A)({userEncryptedResult:t.userEncryptedResult,workspaceEncryptedResults:t.workspaceEncryptedResults,isEncrypted:!0,encryptionMethod:"dual",title:t.title||i||"Encrypted Document",textContent:"[Encrypted Content]",category:c,workspace:t.workspace||(null===p||void 0===p?void 0:p.workspace)||"Default",workspaceIds:l,userId:s,workspaceId:d,status:"completed",fileType:"text/plain",fileSize:0},(null===(A=t.documentImageUrls)||void 0===A?void 0:A.length)>0&&{documentImageUrls:t.documentImageUrls})}else{var j;(0,W.gg)("\ud83c\udd95 Creating new encrypted document from current content");const e=(null===t||void 0===t?void 0:t.editorJson)||t,n={title:t.title||i||"Encrypted Document",editorJson:e,editorHtml:a,textContent:"pdf"===(null===t||void 0===t?void 0:t.viewerMode)&&"string"===typeof t.textContent&&t.textContent.trim()?t.textContent.trim():(a||"").replace(/<[^>]*>/g,""),category:c,workspace:t.workspace||(null===p||void 0===p?void 0:p.workspace)||"Default",fileName:"pdf"===(null===t||void 0===t?void 0:t.viewerMode)?t.fileName||i||"document.pdf":t.title||i||"Encrypted Document",fileType:"pdf"===(null===t||void 0===t?void 0:t.viewerMode)?t.fileType||"application/pdf":"text/plain"},r=await this.encryptionService.encryptDocumentForPersist(n,{actingUserId:s,ownerUserId:t.userId||(null===p||void 0===p?void 0:p.userId)||s,workspaceIds:l,existingDoc:t||p||{}});v=(0,o.A)((0,o.A)({},r),{},{title:n.title,textContent:"[Encrypted Content]",category:c,workspace:n.workspace,userId:t.userId||s,workspaceId:d,status:"completed",fileType:"text/plain",fileSize:n.textContent.length},(null===(j=t.documentImageUrls)||void 0===j?void 0:j.length)>0&&{documentImageUrls:t.documentImageUrls})}else{var N;(0,W.gg)("\ud83d\udcdd Creating plain text document");const e="pdf"===(null===t||void 0===t?void 0:t.viewerMode)&&"string"===typeof t.textContent&&t.textContent.trim()?t.textContent.trim():(a||"").replace(/<[^>]*>/g,""),n=(null===t||void 0===t?void 0:t.editorJson)||t,r="string"===typeof n?n:JSON.stringify(n),u=null!==(N=t.documentImageUrls)&&void 0!==N?N:(()=>{try{const e="string"===typeof n?JSON.parse(n):n;return(0,X.d)(e,50)}catch(e){return[]}})(),m="pdf"===(null===t||void 0===t?void 0:t.viewerMode);v=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({editorJson:r,editorHtml:a,title:i||"Title",fileName:m?t.fileName||i||"document.pdf":i||"Title",textContent:e,workspace:t.workspace||(null===p||void 0===p?void 0:p.workspace)||"Default",workspaceIds:l,fileType:m?t.fileType||"application/pdf":"text/plain",fileSize:m?e.length:(a||"").length,userId:s,workspaceId:d,status:"completed",isEncrypted:!1},void 0!==c&&{category:c}
1),(null===t||void 0===t?void 0:t.timeEntries)&&{timeEntries:t.timeEntries}),void 0!==(null===t||void 0===t?void 0:t.totalTimeLogged)&&{totalTimeLogged:t.totalTimeLogged}),void 0!==(null===t||void 0===t?void 0:t.budgetedHours)&&{budgetedHours:t.budgetedHours}),u.length>0&&{documentImageUrls:u})}"pdf"===(null===t||void 0===t?void 0:t.viewerMode)&&Object.assign(v,y),void 0!==(null===t||void 0===t?void 0:t.paymentLinks)&&(v.paymentLinks=Array.isArray(t.paymentLinks)?t.paymentLinks:[]),p&&(void 0!==p.paymentEnabled&&(v.paymentEnabled=!!p.paymentEnabled),void 0!==p.paymentAmountCents&&(v.paymentAmountCents=null==p.paymentAmountCents||""===p.paymentAmountCents?null:Number(p.paymentAmountCents)),void 0!==p.paymentAmountFieldId&&(v.paymentAmountFieldId=null==p.paymentAmountFieldId||""===p.paymentAmountFieldId?null:p.paymentAmountFieldId),void 0!==p.paymentRevealAfterSignature&&(v.paymentRevealAfterSignature=!!p.paymentRevealAfterSignature),p.formWizardMode&&(v.formWizardMode=p.formWizardMode),void 0!==p.paymentProductName&&(v.paymentProductName=p.paymentProductName||null),void 0!==p.paymentSubscriptionEnabled&&(v.paymentSubscriptionEnabled=!!p.paymentSubscriptionEnabled),void 0!==p.paymentSubscriptionAmountCents&&(v.paymentSubscriptionAmountCents=null==p.paymentSubscriptionAmountCents||""===p.paymentSubscriptionAmountCents?null:Number(p.paymentSubscriptionAmountCents)),void 0!==p.paymentSubscriptionProductName&&(v.paymentSubscriptionProductName=p.paymentSubscriptionProductName||null),void 0!==p.paymentSubscriptionInterval&&(v.paymentSubscriptionInterval=p.paymentSubscriptionInterval||"month"),void 0!==p.enhancementGoal&&(v.enhancementGoal=p.enhancementGoal),void 0!==p.customGoalDescription&&(v.customGoalDescription=p.customGoalDescription||"")),m&&(v.folderId=m);let C=(0,o.A)((0,o.A)((0,o.A)({},v),f?{organizationId:f}:{}),{},{createdAt:(0,B.O5)(),uploadedAt:(0,B.O5)(),updatedAt:(0,B.O5)()});const S=(0,B.doc)((0,B.rJ)(G.db,"knowledgeBaseDocuments")),E=!!v.isEncrypted;E||(0,$.k7)(C,p),C=await(0,$.$X)(C,{docId:S.id,isEncrypted:E,isUpdate:!1});let I=!!C[$.by];try{await(0,B.BN)(S,C)}catch(R){var D;if(te(R))throw console.error("\u274c Firestore rejected document (exceeds 1 MiB):",R),R;if(null!==R&&void 0!==R&&null!==(D=R.message)&&void 0!==D&&D.includes("invalid nested entity")||"invalid-argument"===(null===R||void 0===R?void 0:R.code)){if(console.error("\u274c Firestore rejected document due to nesting:",R),C.editorJson){const e=(await Promise.resolve().then(n.bind(n,5237))).validateAndFixEditorJson;let t=e(C.editorJson),r=t.valid,a=t.fixed,i=t.error;if(!r){console.warn("\u26a0\ufe0f Applying emergency flattening...");const t=e(C.editorJson);t.valid&&(a=t.fixed,r=!0)}if(r&&a){console.warn("\u26a0\ufe0f Retrying save with flattened structure..."),C.editorJson="string"===typeof a?a:JSON.stringify(a),C=await(0,$.$X)(C,{docId:S.id,isEncrypted:E,isUpdate:!1}),I=!!C[$.by],await(0,B.BN)(S,C);const e=new Date,t=(0,o.A)((0,o.A)({},v),{},{id:S.id,isNew:!1,createdAt:e,uploadedAt:e,updatedAt:e,editorJson:C.editorJson},I&&{[$.by]:C[$.by],[$.LY]:C[$.LY]});return(0,o.A)((0,o.A)({},t),{},{_contentModified:!0,_modificationWarning:"Document structure was automatically flattened to ensure compatibility. Some formatting may have been simplified."})}throw new Error("Document structure is too deeply nested for Firestore. ".concat(i||"Please reduce nesting levels to 5-6 maximum."))}throw new Error("Document structure is too deeply nested for Firestore. Please reduce the nesting level of your lists.")}throw R}const P=new Date,T=(0,o.A)((0,o.A)({},v),{},{id:S.id,isNew:!1,createdAt:P,uploadedAt:P,updatedAt:P},I&&{[$.by]:C[$.by],[$.LY]:C[$.LY]});if(await this._isVersionControlActiveForSave(f,h))try{const e=(null===t||void 0===t?void 0:t.editorJson)||t,r=e?"string"===typeof e?e:JSON.stringify(e):null,i=(0,o.A)((0,o.A)({},v),{},{editorJson:r,editorHtml:a||null,textContent:null!==t&&void 0!==t&&t.isEncrypted?"[Encrypted Content]":(a||"").replace(/<[^>]*>/g,""),userId:s}),l=await(0,K.Aj)(S.id,i);if(l){(0,W.gg)("\u2705 Created initial version for new document");try{const e=(await Promise.resolve().then(n.bind(n,18303))).setCurrentVersion;await e(S.id,l),(0,W.gg)("\u2705 Marked initial version as current")}catch(O){console.error("\u26a0\ufe0f Failed to mark initial version as current (non-critical):",O)}}}catch(F){console.error("\u26a0\ufe0f Failed to create initial version (non-critical):",F)}(0,W.gg)("\u2705 Document created successfully:",S.id);try{const e=await Promise.resolve().then(n.bind(n,20438));(0,e.recordDocCreatedEvent)(S.id)}catch(L){}return T}async _updateDocument(e,t,r){var a;const i=r.html,s=r.title,l=r.userId,d=r.workspaceIds,c=r.categoryToSave,u=r.folderIdToSave,m=void 0===u?null:u,p=r.currentDoc,g=r.originalDoc,h=r.versionControlEnabled,f=void 0!==h&&h,y=r.organizationId,v=r.isManualSave,x=void 0!==v&&v;(0,W.gg)("\ud83d\udcdd Updating document:",e);const b=(null===p||void 0===p?void 0:p.restoredFromVersion)||(null===g||void 0===g?void 0:g.restoredFromVersion),w=(null===p||void 0===p?void 0:p.restoredAt)||(null===g||void 0===g?void 0:g.restoredAt),k=Date.now(),A=(null===w||void 0===w||null===(a=w.toMillis)||void 0===a?void 0:a.call(w))||(w instanceof Date?w.getTime():null),j=!(b&&(A&&k-A<1e4))&&await this._isVersionControlA
1ctiveForSave(y,f);if(null!==t&&void 0!==t&&t.isEncrypted){var N;let r;if((0,W.gg)("\ud83d\udd12 Updating encrypted document"),"dual"===t.encryptionMethod){var C;const e=(null===g||void 0===g?void 0:g.userId)||(null===p||void 0===p?void 0:p.userId),n=Boolean(e&&l&&e!==l),a=(null===g||void 0===g?void 0:g.userEncryptedResult)||(null===p||void 0===p?void 0:p.userEncryptedResult);r=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({userEncryptedResult:n&&a?a:t.userEncryptedResult,workspaceEncryptedResults:t.workspaceEncryptedResults,isEncrypted:!0,encryptionMethod:"dual",title:s,textContent:"[Encrypted Content]",editorJson:(0,B.CL)(),editorHtml:(0,B.CL)(),workspace:(null===g||void 0===g?void 0:g.workspace)||(null===p||void 0===p?void 0:p.workspace)||(null===t||void 0===t?void 0:t.workspace)||"Default",workspaceIds:d,status:(null===g||void 0===g?void 0:g.status)||(null===p||void 0===p?void 0:p.status)||"completed",updatedAt:(0,B.O5)()},void 0!==c&&{category:c}),m&&{folderId:m}),null!==t&&void 0!==t&&t.timeEntries?{timeEntries:t.timeEntries}:null!==p&&void 0!==p&&p.timeEntries?{timeEntries:p.timeEntries}:{}),void 0!==(null===t||void 0===t?void 0:t.totalTimeLogged)?{totalTimeLogged:t.totalTimeLogged}:void 0!==(null===p||void 0===p?void 0:p.totalTimeLogged)?{totalTimeLogged:p.totalTimeLogged}:{}),void 0!==(null===t||void 0===t?void 0:t.budgetedHours)?{budgetedHours:t.budgetedHours}:void 0!==(null===p||void 0===p?void 0:p.budgetedHours)?{budgetedHours:p.budgetedHours}:{}),void 0!==(null===g||void 0===g?void 0:g.locked)&&{locked:g.locked}),(null===g||void 0===g?void 0:g.unlockPhraseHash)&&{unlockPhraseHash:g.unlockPhraseHash}),(null===(C=t.documentImageUrls)||void 0===C?void 0:C.length)>0&&{documentImageUrls:t.documentImageUrls})}else{(0,W.gg)("\ud83d\udd04 Converting legacy encryption to dual during update");try{const e=await(0,Y.k5)(l),n=await(0,Y.PV)(t.encryptedResult,e);if(!n)throw new Error("Failed to decrypt legacy content");{var S;const e=JSON.parse(n);if(e.editorJson){const t=(0,Z.validateAndFixEditorJson)(e.editorJson),n=t.valid,r=t.fixed,o=t.error,a=t.wasFixed;n&&r?(e.editorJson=r,a&&console.warn("\u26a0\ufe0f editorJson was automatically fixed before encryption")):console.error("\u274c editorJson validation failed before encryption:",o)}const a=await this.encryptionService.encryptDocumentForPersist(e,{actingUserId:l,ownerUserId:(null===g||void 0===g?void 0:g.userId)||(null===p||void 0===p?void 0:p.userId),workspaceIds:d,existingDoc:g||p||{}}),i=e.editorJson?"string"===typeof e.editorJson?e.editorJson:JSON.stringify(e.editorJson):null;r=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({},a),{},{title:s,textContent:"[Encrypted Content]",editorJson:(0,B.CL)(),editorHtml:(0,B.CL)(),workspace:(null===g||void 0===g?void 0:g.workspace)||(null===p||void 0===p?void 0:p.workspace)||(null===t||void 0===t?void 0:t.workspace)||"Default",status:(null===g||void 0===g?void 0:g.status)||(null===p||void 0===p?void 0:p.status)||"completed",updatedAt:(0,B.O5)()},void 0!==c&&{category:c}),void 0!==(null===g||void 0===g?void 0:g.locked)&&{locked:g.locked}),(null===g||void 0===g?void 0:g.unlockPhraseHash)&&{unlockPhraseHash:g.unlockPhraseHash}),(null===(S=t.documentImageUrls)||void 0===S?void 0:S.length)>0&&{documentImageUrls:t.documentImageUrls}),r._validatedEditorJson=i}}catch(R){var E;console.error("\u274c Failed to convert legacy encryption during update:",R),r=(0,o.A)((0,o.A)((0,o.A)((0,o.A)({encryptedResult:t.encryptedResult,isEncrypted:!0,encryptionMethod:"legacy",title:s,textContent:"[Encrypted Content]",editorJson:(0,B.CL)(),editorHtml:(0,B.CL)(),workspace:(null===g||void 0===g?void 0:g.workspace)||(null===p||void 0===p?void 0:p.workspace)||(null===t||void 0===t?void 0:t.workspace)||"Default",workspaceIds:d,status:(null===g||void 0===g?void 0:g.status)||(null===p||void 0===p?void 0:p.status)||"completed",updatedAt:(0,B.O5)()},void 0!==c&&{category:c}),void 0!==(null===g||void 0===g?void 0:g.locked)&&{locked:g.locked}),(null===g||void 0===g?void 0:g.unlockPhraseHash)&&{unlockPhraseHash:g.unlockPhraseHash}),(null===(E=t.documentImageUrls)||void 0===E?void 0:E.length)>0&&{documentImageUrls:t.documentImageUrls})}}const a=r._validatedEditorJson;delete r._validatedEditorJson,void 0!==(null===t||void 0===t?void 0:t.paymentLinks)&&(r.paymentLinks=Array.isArray(t.paymentLinks)?t.paymentLinks:[]),r=await(0,$.$X)(r,{docId:e,isEncrypted:!0,isUpdate:!0});try{await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",e),r)}catch(R){var I;if(te(R))throw console.error("\u274c Firestore rejected update (exceeds 1 MiB):",R),R;if(null!==R&&void 0!==R&&null!==(I=R.message)&&void 0!==I&&I.includes("invalid nested entity")||"invalid-argument"===(null===R||void 0===R?void 0:R.code)){if(console.error("\u274c Firestore rejected update due to nesting:",R),null!==t&&void 0!==t&&t.editorJson){const a=(await Promise.resolve().then(n.bind(n,5237))).validateAndFixEditorJson;let i=a(t.editorJson),u=i.valid,m=i.fixed,h=i.error;if(!u){console.warn("\u26a0\ufe0f Applying emergency flattening to encrypted update...");const e=a(t.editorJson);e.valid&&(m=e.fixed,u=!0)}if(u&&m){var D;console.warn("\u26a0\ufe0f Retrying encrypted update with validated and flattened content...");const n=(0,o.A)((0,o.A)({},JSON.parse(await(0,Y.PV)(t.encryptedResult||t.userEncryptedResult,await(0,Y.k5)(l)))),{},{editorJson:m}),a=await this.encryptionService.encryptDocumentForPersist(n,{actingUserId:l,ownerUserId:(null===g||void 0===g?void 0:g.userId)||(null===p||void 0===p?void 0:p.userId),workspaceIds:d,existingDoc:g||p||{}});return r=(0,o.A)((0,o.A)((0,o.A)((0,o.A)({},a),{},{title:s,workspace:(null===g||void 0===g?void 0:g.workspace)||(null===p||void 0===p?void 0:p.workspace)||(null===t||void 0===t?void 0:t.workspace)||"Default",status:(null===g||void 0===g?void 0:g.status)||(null===p||void 0===p?void 0:p.status)||"completed",updatedAt:(0,B.O5)()},void 0!==c&&{category:c}),void 0!==(null===g||void 0===g?void 0:g.locked)&&{locked:g.locked}),(null===g||void 0===g?void 0:g.unlockPhraseHash)&&{unlockPhraseHash:g.unlockPhraseHash}),r=await(0,$.$X)(r,{docId:e,isEncrypted:!0,isUpdate:!0}),await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",e),r),(0,o.A)((0,o.A)((0,o.A)({},r),{},{id:e,title:s||(null===(D=r)||void 0===D?void 0:D.title)||(null===p||void 0===p?void 0:p.title),textContent:"[Encrypted Content]"},void 0!==c&&{category:c}),{},{_contentModified:!0,_modificationWarning:"Document structure was automatically flattened to ensure compatibility. Some formatting may have been simplified."})}throw new Error("Document structure is too deeply nested for Firestore. ".concat(h||"Please reduce nesting levels to 5-6 maximum."))}throw new Error("Document structure is too deeply nested for Firestore. Please reduce the nesting level of your lists.")}throw R}return j&&await this._createVersionIfNeeded(e,(0,o.A)((0,o.A)({},r),{},{editorJson:(()=>{const e=a||(null===t||void 0===t?void 0:t.editorJson)||(null===p||void 0===p?void 0:p.editorJson)||null;return e?"string"===typeof e?e:JSON.stringify(e):null})(),editorHtml:i||(null===p||void 0===p?void 0:p.editorHtml)||null,userId:l}
1),{forceVersion:Boolean(x)}),(0,o.A)((0,o.A)({},r),{},{id:e,title:s||(null===(N=r)||void 0===N?void 0:N.title)||(null===p||void 0===p?void 0:p.title),textContent:"[Encrypted Content]"},void 0!==c&&{category:c})}{var P;(0,W.gg)("\ud83d\udcdd Updating plain text document");const r=(null===t||void 0===t?void 0:t.editorJson)||t,a="string"===typeof r?r:JSON.stringify(r),u="pdf"===(null===t||void 0===t?void 0:t.viewerMode)||"pdf"===(null===p||void 0===p?void 0:p.viewerMode)||"pdf"===(null===g||void 0===g?void 0:g.viewerMode),h=null!==(P=t.documentImageUrls)&&void 0!==P?P:(()=>{try{const e="string"===typeof r?JSON.parse(r):r;return(0,X.d)(e,50)}catch(e){return[]}})(),f=u&&"string"===typeof t.textContent&&t.textContent.trim()?t.textContent.trim():u&&((null===p||void 0===p?void 0:p.textContent)||(null===g||void 0===g?void 0:g.textContent))||"";let y=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({editorJson:a,editorHtml:i,title:s,fileName:u?t.fileName||(null===p||void 0===p?void 0:p.fileName)||(null===g||void 0===g?void 0:g.fileName)||"document.pdf":s,textContent:u?f:(i||"").replace(/<[^>]*>/g,""),updatedAt:(0,B.O5)(),workspace:(null===g||void 0===g?void 0:g.workspace)||(null===p||void 0===p?void 0:p.workspace)||"Default",workspaceIds:d},!u&&(null===g||void 0===g?void 0:g.fileType)&&{fileType:g.fileType}),u&&{fileType:t.fileType||(null===p||void 0===p?void 0:p.fileType)||(null===g||void 0===g?void 0:g.fileType)||"application/pdf"}),{},{status:(null===g||void 0===g?void 0:g.status)||(null===p||void 0===p?void 0:p.status)||"completed",isEncrypted:!1,fileSize:u&&"string"===typeof f?f.length:(i||"").length},void 0!==c&&{category:c}),m&&{folderId:m}),null!==t&&void 0!==t&&t.timeEntries?{timeEntries:t.timeEntries}:null!==p&&void 0!==p&&p.timeEntries?{timeEntries:p.timeEntries}:{}),void 0!==(null===t||void 0===t?void 0:t.totalTimeLogged)?{totalTimeLogged:t.totalTimeLogged}:void 0!==(null===p||void 0===p?void 0:p.totalTimeLogged)?{totalTimeLogged:p.totalTimeLogged}:{}),void 0!==(null===t||void 0===t?void 0:t.budgetedHours)?{budgetedHours:t.budgetedHours}:void 0!==(null===p||void 0===p?void 0:p.budgetedHours)?{budgetedHours:p.budgetedHours}:{}),void 0!==(null===g||void 0===g?void 0:g.locked)&&{locked:g.locked}),(null===g||void 0===g?void 0:g.unlockPhraseHash)&&{unlockPhraseHash:g.unlockPhraseHash}),void 0!==(null===t||void 0===t?void 0:t.paymentLinks)&&{paymentLinks:Array.isArray(t.paymentLinks)?t.paymentLinks:[]}),h.length>0&&{documentImageUrls:h});if(u){const e=t.url||(null===p||void 0===p?void 0:p.url)||(null===g||void 0===g?void 0:g.url)||null,n=t.previewUrl||t.url||(null===p||void 0===p?void 0:p.previewUrl)||(null===p||void 0===p?void 0:p.url)||(null===g||void 0===g?void 0:g.previewUrl)||(null===g||void 0===g?void 0:g.url)||null;Object.assign(y,{viewerMode:"pdf",url:e,previewUrl:n})}(0,$.k7)(y,p||g),y=await(0,$.$X)(y,{docId:e,isEncrypted:!1,isUpdate:!0});try{await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",e),y)}catch(R){var T;if(te(R))throw console.error("\u274c Firestore rejected update (exceeds 1 MiB):",R),R;if(null!==R&&void 0!==R&&null!==(T=R.message)&&void 0!==T&&T.includes("invalid nested entity")||"invalid-argument"===(null===R||void 0===R?void 0:R.code)){if(console.error("\u274c Firestore rejected update due to nesting:",R),y.editorJson){const t=(await Promise.resolve().then(n.bind(n,5237))).validateAndFixEditorJson;let r=t(y.editorJson),a=r.valid,i=r.fixed,s=r.error;if(!a){console.warn("\u26a0\ufe0f Applying emergency flattening...");const e=t(y.editorJson);e.valid&&(i=e.fixed,a=!0)}if(a&&i)return console.warn("\u26a0\ufe0f Retrying update with flattened structure..."),y.editorJson="string"===typeof i?i:JSON.stringify(i),y=await(0,$.$X)(y,{docId:e,isEncrypted:!1,isUpdate:!0}),await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",e),y),(0,o.A)((0,o.A)({},y),{},{id:e,_contentModified:!0,_modificationWarning:"Document structure was automatically flattened to ensure compatibility. Some formatting may have been simplified."});throw new Error("Document structure is too deeply nested for Firestore. ".concat(s||"Please reduce nesting levels to 5-6 maximum."))}throw new Error("Document structure is too deeply nested for Firestore. Please reduce the nesting level of your lists.")}throw R}return j&&await this._createVersionIfNeeded(e,(0,o.A)((0,o.A)({},y),{},{userId:l}
1),{forceVersion:Boolean(x)}),(0,o.A)((0,o.A)({},y),{},{id:e})}}async _createVersionIfNeeded(e,t){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{const a=await(0,K.Aj)(e,t,r);if(a){(0,W.gg)("\u2705 Created version for document update");try{const t=(await Promise.resolve().then(n.bind(n,18303))).setCurrentVersion;await t(e,a),(0,W.gg)("\u2705 Marked newly created version as current")}catch(o){console.error("\u26a0\ufe0f Failed to mark version as current (non-critical):",o)}}else(0,W.gg)("\u23ed\ufe0f Skipped version creation - content unchanged");return a}catch(a){return console.error("\u26a0\ufe0f Failed to create version (non-critical):",a),null}}};var re=n(20669),oe=n(84441),ae=n(95523);const ie=new class{constructor(){this.savingDocuments=new Set,this.justCreatedDocs=new Set,this.lastSaveTimestamps=new Map,this.creatingDocuments=new Set}isSaving(e){return this.savingDocuments.has(String(e))}markSaving(e){const t=String(e);this.savingDocuments.add(t),this.lastSaveTimestamps.set(t,Date.now()),(0,W.gg)("\ud83d\udcbe Marked document as saving:",t)}markSaved(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2500;const n=String(e);if(/^new_|^temp_/.test(n))return this.savingDocuments.delete(n),void(0,W.gg)("\ud83d\udcbe Cleared save flag for temp ID:",n);setTimeout(()=>{this.savingDocuments.delete(n),(0,W.gg)("\ud83d\udcbe Cleared save flag for document:",n)},t)}markJustCreated(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:3e3;const n=String(e);this.justCreatedDocs.add(n),(0,W.gg)("\u2728 Marked document as just created:",n),setTimeout(()=>{this.justCreatedDocs.delete(n),(0,W.gg)("\u2728 Cleared just-created flag for document:",n)},t)}isJustCreated(e){return this.justCreatedDocs.has(String(e))}markCreating(e){const t=String(e);this.creatingDocuments.add(t),(0,W.gg)("\ud83d\udd28 Marked document as being created:",t)}isCreating(e){return this.creatingDocuments.has(String(e))}clearCreating(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1e3;const n=String(e);setTimeout(()=>{this.creatingDocuments.delete(n),(0,W.gg)("\ud83d\udd13 Cleared creating flag for document:",n)},t)}shouldSkipSnapshot(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:2e3;const n=String(e);if(this.isSaving(n))return(0,W.gg)("\u23ed\ufe0f Skipping snapshot - document is saving:",n),!0;if(this.isJustCreated(n))return(0,W.gg)("\u23ed\ufe0f Skipping snapshot - document just created:",n),!0;const r=this.lastSaveTimestamps.get(n);if(r){const e=Date.now()-r;if(e<t)return(0,W.gg)("\u23ed\ufe0f Skipping snapshot - recent save detected:",n,"(".concat(e,"ms ago)")),!0}return!1}getLastSaveTime(e){return this.lastSaveTimestamps.get(String(e))||null}clear(){this.savingDocuments.clear(),this.justCreatedDocs.clear(),this.lastSaveTimestamps.clear(),this.creatingDocuments.clear(),(0,W.gg)("\ud83e\uddf9 Cleared all document save state")}};var se=n(35417);const le=["id"],de=["id"];function ce(e){if(!e)return"";const t=e.workspaceSearchIndexAt,n=t&&"function"===typeof t.toMillis?t.toMillis():null!=(null===t||void 0===t?void 0:t.seconds)?1e3*t.seconds+Math.floor((t.nanoseconds||0)/1e6):"";return[e.workspaceSearchIndexStatus||"",e.workspaceSearchIndexError||"",String(n)].join("\0")}function ue(e){if(!e)return e;const t=e;if("string"===typeof e)try{const n=JSON.parse(e);return null===n||void 0===n?(console.warn("\u26a0\ufe0f normalizeEditorJson: Parsed result is null/undefined, preserving original string"),t):n}catch(n){return console.error("\u274c Error parsing editorJson string:",n),t}return null===e||void 0===e?(console.warn("\u26a0\ufe0f normalizeEditorJson: Input is null/undefined"),e):e}function me(e,t){if(!e)return!0;if(!t)return!1;if(t.isEncrypted||e.isEncrypted){return JSON.stringify({title:e.title,category:e.category,workspace:e.workspace,workspaceIds:e.workspaceIds,workspaceId:e.workspaceId,timeEntries:e.timeEntries,totalTimeLogged:e.totalTimeLogged,budgetedHours:e.budgetedHours,paymentEnabled:e.paymentEnabled,paymentAmountCents:e.paymentAmountCents,paymentAmountFieldId:e.paymentAmountFieldId,paymentRevealAfterSignature:e.paymentRevealAfterSignature,paymentProductName:e.paymentProductName,paymentReminderEnabled:e.paymentReminderEnabled,paymentLinks:e.paymentLinks,paymentSubscriptionEnabled:e.paymentSubscriptionEnabled,paymentSubscriptionAmountCents:e.paymentSubscriptionAmountCents,paymentSubscriptionProductName:e.paymentSubscriptionProductName,paymentSubscriptionInterval:e.paymentSubscriptionInterval,mascotBackgroun
1d:e.mascotBackground,_idx:ce(e)})===JSON.stringify({title:t.title,category:t.category,workspace:t.workspace,workspaceIds:t.workspaceIds,workspaceId:t.workspaceId,timeEntries:t.timeEntries,totalTimeLogged:t.totalTimeLogged,budgetedHours:t.budgetedHours,paymentEnabled:t.paymentEnabled,paymentAmountCents:t.paymentAmountCents,paymentAmountFieldId:t.paymentAmountFieldId,paymentRevealAfterSignature:t.paymentRevealAfterSignature,paymentProductName:t.paymentProductName,paymentReminderEnabled:t.paymentReminderEnabled,paymentLinks:t.paymentLinks,paymentSubscriptionEnabled:t.paymentSubscriptionEnabled,paymentSubscriptionAmountCents:t.paymentSubscriptionAmountCents,paymentSubscriptionProductName:t.paymentSubscriptionProductName,paymentSubscriptionInterval:t.paymentSubscriptionInterval,mascotBackground:t.mascotBackground,_idx:ce(t)})?((0,W.gg)("\u23ed\ufe0f Skipping onSnapshot update for encrypted document - no metadata change"),!1):((0,W.gg)("\ud83d\udcdd Updating encrypted document metadata while preserving decrypted content"),!0)}return JSON.stringify({title:e.title,editorJson:e.editorJson,editorHtml:e.editorHtml,category:e.category,workspaceIds:e.workspaceIds,timeEntries:e.timeEntries,totalTimeLogged:e.totalTimeLogged,budgetedHours:e.budgetedHours,paymentEnabled:e.paymentEnabled,paymentAmountCents:e.paymentAmountCents,paymentAmountFieldId:e.paymentAmountFieldId,paymentRevealAfterSignature:e.paymentRevealAfterSignature,paymentProductName:e.paymentProductName,paymentReminderEnabled:e.paymentReminderEnabled,paymentLinks:e.paymentLinks,paymentSubscriptionEnabled:e.paymentSubscriptionEnabled,paymentSubscriptionAmountCents:e.paymentSubscriptionAmountCents,paymentSubscriptionProductName:e.paymentSubscriptionProductName,paymentSubscriptionInterval:e.paymentSubscriptionInterval,mascotBackground:e.mascotBackground,_idx:ce(e)})!==JSON.stringify({title:t.title,editorJson:t.editorJson,editorHtml:t.editorHtml,category:t.category,workspaceIds:t.workspaceIds,timeEntries:t.timeEntries,totalTimeLogged:t.totalTimeLogged,budgetedHours:t.budgetedHours,paymentEnabled:t.paymentEnabled,paymentAmountCents:t.paymentAmountCents,paymentAmountFieldId:t.paymentAmountFieldId,paymentRevealAfterSignature:t.paymentRevealAfterSignature,paymentProductName:t.paymentProductName,paymentReminderEnabled:t.paymentReminderEnabled,paymentLinks:t.paymentLinks,paymentSubscriptionEnabled:t.paymentSubscriptionEnabled,paymentSubscriptionAmountCents:t.paymentSubscriptionAmountCents,paymentSubscriptionProductName:t.paymentSubscriptionProductName,paymentSubscriptionInterval:t.paymentSubscriptionInterval,mascotBackground:t.mascotBackground,_idx:ce(t)})||((0,W.gg)("\u23ed\ufe0f Skipping onSnapshot update - no meaningful content change"),!1)}function pe(e,t){if(!e)return t;if(t.isEncrypted||e.isEncrypted){(0,W.gg)("\ud83d\udd12 Merging encrypted document update - preserving decrypted content",{hasPrevEditorJson:!!e.editorJson,hasPrevEditorHtml:!!e.editorHtml,hasNewEditorJson:!!t.editorJson,hasNewEditorHtml:!!t.editorHtml,prevIsDecrypted:e.isDecrypted}),e.editorJson&&!t.editorJson?(0,W.gg)("\u2705 Preserving decrypted editorJson from prev (Firestore has no decrypted content)"):!e.editorJson&&t.editorJson?(0,W.gg)("\u26a0\ufe0f WARNING: prev has no editorJson but newDoc does - this is unexpected for encrypted doc"):e.editorJson||t.editorJson||(0,W.gg)("\u26a0\ufe0f WARNING: Both prev and newDoc lack editorJson - document may appear blank");if(JSON.stringify({title:e.title,category:e.category,workspace:e.workspace,workspaceIds:e.workspaceIds,workspaceId:e.workspaceId,timeEntries:e.timeEntries,totalTimeLogged:e.totalTimeLogged,budgetedHours:e.budgetedHours,mascotBackground:e.mascotBackground,_idx:ce(e)})===JSON.stringify({title:t.title,category:t.category,workspace:t.workspace,workspaceIds:t.workspaceIds,workspaceId:t.workspaceId,timeEntries:t.timeEntries,totalTimeLogged:t.totalTimeLogged,budgetedHours:t.budgetedHours,mascotBackground:t.mascotBackground,_idx:ce(t)}))return e;const n=ue(e.editorJson||t.editorJson),a=n||(e.editorJson?e.editorJson:null),i=(t.id,(0,r.A)(t,le)),s=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({},void 0!==e.paymentEnabled&&void 0===t.paymentEnabled&&{paymentEnabled:e.paymentEnabled}),!0===e.paymentEnabled&&!1===t.paymentEnabled&&{paymentEnabled:!0}),void 0!==e.paymentAmountCents&&void 0===t.paymentAmountCents&&{paymentAmountCents:e.paymentAmountCents}),void 0!==e.paymentAmountFieldId&&void 0===t.paymentAmountFieldId&&{paymentAmountFieldId:e.paymentAmountFieldId}),void 0!==e.paymentRevealAfterSignature&&void 0===t.paymentRevealAfterSignature&&{paymentRevealAfterSignature:e.paymentRevealAfterSignature}),void 0!==e.formWizardMode&&void 0===t.formWizardMode&&{formWizardMode:e.formWizardMode}),void 0!==e.paymentProductName&&void 0===t.paymentProductName&&{paymentProductName:e.paymentProductName}),void 0!==e.paymentReminderEnabled&&void 0===t.paymentReminderEnabled&&{paymentReminderEnabled:e.paymentReminderEnabled}),!0===e.paymentReminderEnabled&&!1===t.paymentReminderEnabled&&{paymentReminderEnabled:!0}),void 0!==e.paymentLinks&&void 0===t.paymentLinks&&{paymentLinks:e.paymentLinks}),void 0!==e.paymentSubscriptionEnabled&&void 0===t.paymentSubscriptionEnabled&&{paymentSubscriptionEnabled:e.paymentSubscriptionEnabled}),!0===e.paymentSubscriptionEnabled&&!1===t.paymentSubscriptionEnabled&&{paymentSubscriptionEnabled:!0}),void 0!==e.paymentSubscriptionAmountCents&&void 0===t.paymentSubscriptionAmountCents&&{paymentSubscriptionAmountCents:e.paymentSubscriptionAmountCents}),void 0!==e.paymentSubscriptionProductName&&void 0===t.paymentSubscriptionProductName&&{paymentSubscriptionProductName:e.paymentSubscriptionProductName}),void 0!==e.paymentSubscriptionInterval&&void 0===t.paymentSubscriptionInterval&&{paymentSubscriptionInterval:e.paymentSubscriptionInterval}),l=(0,o.A)((0,o.A)({},i),{},{id:e.id,editorJson:a,editorHtml:e.editorHtml||t.editorHtml,textContent:e.textContent||t.textContent,isDecrypted:e.isDecrypted||!1},s);if(!l.editorJson&&e.editorJson){console.error("\u274c CRITICAL: Lost editorJson during onSnapshot update for encrypted document!"),(0,W.gg)("\u274c This should not happen - editorJson was lost",{prevHadEditorJson:!!e.editorJson,normalizedResult:n,finalEditorJson:a});t.id;const i=(0,r.A)(t,de);return(0,o.A)((0,o.A)((0,o.A)({},e),i),{},{id:e.id,editorJson:e.editorJson,editorHtml:e.editorHtml,textContent:e.textContent,isDecrypted:e.isDecrypted},s)}return l}const n=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({},void 0!==e.paymentEnabled&&void 0===t.paymentEnabled&&{paymentEnabled:e.paymentEnabled}),!0===e.paymentEnabled&&!1===t.paymentEnabled&&{paymentEnabled:!0}),void 0!==e.paymentAmountCents&&void 0===t.paymentAmountCents&&{paymentAmountCents:e.paymentAmountCents}),void 0!==e.paymentAmountFieldId&&void 0===t.paymentAmountFieldId&&{paymentAmountFieldId:e.paymentAmountFieldId}),void 0!==e.paymentRevealAfterSignature&&void 0===t.paymentRevealAfterSignature&&{paymentRevealAfterSignature:e.paymentRevealAfterSignature}),void 0!==e.formWizardMode&&void 0===t.formWizardMode&&{formWizardMode:e.formWizardMode}),void 0!==e.paymentProductName&&void 0===t.paymentProductName&&{paymentProductName:e.paymentProductName}),void 0!==e.paymentReminderEnabled&&void 0===t.paymentReminderEnabled&&{paymentReminderEnabled:e.paymentReminderEnabled}),!0===e.paymentReminderEnabled&&!1===t.paymentReminderEnabled&&{paymentReminderEnabled:!0}),void 0!==e.paymentLinks&&void 0===t.paymentLinks&&{paymentLinks:e.paymentLinks}),void 0!==e.paymentSubscriptionEnabled&&void 0===t.paymentSubscriptionEnabled&&{paymentSubscriptionEnabled:e.paymentSubscriptionEnabled}),!0===e.paymentSubscriptionEnabled&&!1===t.paymentSubscriptionEnabled&&{paymentSubscriptionEnabled:!0}),void 0!==e.paymentSubscriptionAmountCents&&void 0===t.paymentSubscriptionAmountCents&&{paymentSubscriptionAmountCents:e.paymentSubscriptionAmountCents}),void 0!==e.paymentSubscriptionProductName&&void 0===t.paymentSubscriptionProductName&&{paymentSubscriptionProductName:e.paymentSubscriptionProductName}),void 0!==e.paymentSubscriptionInterval&&void 0===t.paymentSubscriptionInterval&&{paymentSubscriptionInterval:e.paymentSubscriptionInterval});return t.editorJson&&"string"===typeof t.editorJson?(0,o.A)((0,o.A)({},t),{},{editorJson:ue(t.editorJson)},n):(0,o.A)((0,o.A)({},t),n)}var ge=n(52395),he=n(67898),fe=n(70067),ye=n(25040),ve=n(95919),xe=n(42574),be=n(27033),we=n(94805),ke=n(15711),Ae=n(14459),je=n(82300),Ne=n(67588),Ce=n(19233),Se=n(66630),Ee=n(58147),Ie=n(92339),De=n(32228),Pe=n(47081),Te=n(13471),Re=n(98315),Oe=n(92298);function Fe(e){if(!e||"object"!==typeof e)return{headerImageUrl:"",coverImageUrl:"",chatbotImageUrl:"",headerTitle:"",workspaceTheme:null};return{headerImageUrl:"string"===typeof e.headerImageUrl?e.headerImageUrl:"",coverImageUrl:"string"===typeof e.coverImageUrl?e.coverImageUrl:"",chatbotImageUrl:"string"===typeof e.chatbotImageUrl?e.chatbotImageUrl:"",headerTitle:"string"===typeof e.headerTitle?e.headerTitle:"",workspaceTheme:null==e.workspaceTheme||"object"!==typeof e.workspaceTheme||Array.isArray(e.workspaceTheme)?null:e.workspaceTheme}}var Le=n(55634),_e=n(86353),Ue=n(77052),Me=n(78324),ze=n(60492),Be=n(42773),We=n(70579);function Ve(e){const t=null===e||void 0===e?void 0:e.createdAt;return t&&"function"===typeof t.toMillis?t.toMillis():t&&"number"===typeof t.seconds?1e3*t.seconds:0}const Je=[{name:"Blue",hex:"#2563eb"},{name:"Bright blue",hex:"#3b82f6"},{name:"Dark",hex:"#1f2937"},{name:"Green",hex:"#10b981"},{name:"Purple",hex:"#8b5cf6"},{name:"Orange",hex:"#f59e0b"}];function qe(e,t){const n=(e||"").trim();if(n)return n;const r=(t||"").trim();return r||"This workspace"}function He(e,t){const n=qe(e,t),r=/^this workspace$/i.test(n),o=function(e){return!e||/^this workspace$/i.test(e)?"This workspace's":/s$/i.test(e)?"".concat(e,"'"):"".concat(e,"'s")}(n);return{name:r?"Workspace assistant":"".concat(o," Assistant"),description:r?"AI assistant that answers visitor questions using this shared workspace.":"AI assistant that answers visitor questions using ".concat(o," shared content."),welcomeMessage:r?"Hi! I can help visitors find information in this workspace. What would you like to know?":"Hi! I can help visitors find information in ".concat(o," workspace. What would you like to know?"),placeholder:r?"Ask about this workspace...":"Ask ".concat(o," assistant...")}}function Ge(e){let t=e.url,n=e.fallbackUrl;const r=(0,i.useState)(!1),o=(0,a.A)(r,2),s=o[0],l=o[1],d=(t||"").trim()||null,c=(n||"").trim()||null,u=d||c||null;return(0,i.useEffect)(()=>
1{l(!1)},[u]),u?s?(0,We.jsx)(fe.A,{className:"w-7 h-7 text-gray-300",title:"Could not load preview"}):(0,We.jsx)("img",{src:u,alt:"",referrerPolicy:"no-referrer",className:"w-full h-full object-contain p-0.5",onError:()=>l(!0)},u):(0,We.jsx)(fe.A,{className:"w-7 h-7 text-gray-300"})}function Ke(e,t){return(0,o.A)((0,o.A)({},He(e,t)),{},{theme:"default",position:"bottom-right",size:"medium",branding:!0,visitorPdfAccessForChat:!0})}function Qe(e,t,n){const r=Ke(t,n);return e&&"object"===typeof e?(0,o.A)((0,o.A)({},r),e):r}const Ye=e=>{let t=e.workspaceId,n=e.workspaceName,r=void 0===n?"":n,s=e.knowledgeBase,c=e.isOpen,u=e.onClose,m=e.onSave,h=e.onDelete,v=e.currentLink,x=void 0===v?null:v,k=e.forcePublic,A=void 0!==k&&k,j=e.documentId,N=void 0===j?null:j,C=e.organizationId,S=void 0===C?null:C,E=e.preferredExternalAgentId,I=void 0===E?null:E,D=e.documentOnlyShare,P=void 0!==D&&D,T=e.mascotEnabled,O=void 0!==T&&T;(0,W.gg)("Modal component rendered with:",{isOpen:c,knowledgeBaseId:null===s||void 0===s?void 0:s.id,currentLink:x,workspaceId:t,documentId:N});const F=(0,i.useState)(""),L=(0,a.A)(F,2),_=L[0],U=L[1],M=(0,i.useState)(!1),z=(0,a.A)(M,2),V=z[0],J=z[1],q=(0,i.useState)(!0),H=(0,a.A)(q,2),K=H[0],Q=H[1],Y=(0,i.useState)(!1),Z=(0,a.A)(Y,2),$=Z[0],X=Z[1],ee=(0,i.useState)(""),te=(0,a.A)(ee,2),ne=te[0],re=te[1],oe=(0,i.useState)(""),ae=(0,a.A)(oe,2),ie=ae[0],se=ae[1],le=(0,i.useState)(!0),de=(0,a.A)(le,2),ce=de[0],ue=de[1],me=(0,i.useState)(null),pe=(0,a.A)(me,2),Le=pe[0],Ye=pe[1],Ze=(0,i.useState)(!1),$e=(0,a.A)(Ze,2),Xe=$e[0],et=$e[1],tt=(0,i.useRef)(null),nt=(0,i.useRef)(Promise.resolve()),rt=(0,i.useRef)(!1),ot=(0,i.useRef)(null),at=(0,i.useState)(!0),it=(0,a.A)(at,2),st=it[0],lt=it[1],dt=(0,i.useState)(!0),ct=(0,a.A)(dt,2),ut=ct[0],mt=ct[1],pt=(0,i.useState)(!1),gt=(0,a.A)(pt,2),ht=gt[0],ft=gt[1],yt=(0,i.useState)(!1),vt=(0,a.A)(yt,2),xt=vt[0],bt=vt[1],wt=(0,i.useState)(!1),kt=(0,a.A)(wt,2),At=kt[0],jt=kt[1],Nt=(0,i.useState)(!1),Ct=(0,a.A)(Nt,2),St=Ct[0],Et=Ct[1],It=(0,i.useState)(!1),Dt=(0,a.A)(It,2),Pt=Dt[0],Tt=Dt[1],Rt=(0,i.useRef)(null),Ot=(0,i.useState)(!1),Ft=(0,a.A)(Ot,2),Lt=Ft[0],_t=Ft[1],Ut=(0,i.useState)(N?"document":"workspace"),Mt=(0,a.A)(Ut,2),zt=Mt[0],Bt=Mt[1],Wt=(0,i.useState)(N),Vt=(0,a.A)(Wt,2),Jt=Vt[0],qt=Vt[1],Ht=(0,i.useState)("both"),Gt=(0,a.A)(Ht,2),Kt=Gt[0],Qt=Gt[1],Yt=(0,i.useState)(!1),Zt=(0,a.A)(Yt,2),$t=Zt[0],Xt=Zt[1],en=(0,i.useState)(!1),tn=(0,a.A)(en,2),nn=tn[0],rn=tn[1],on=(0,i.useState)("link"),an=(0,a.A)(on,2),sn=an[0],ln=an[1],dn=(0,i.useState)(""),cn=(0,a.A)(dn,2),un=cn[0],mn=cn[1],pn=(0,i.useState)(De.O9),gn=(0,a.A)(pn,2),hn=gn[0],fn=gn[1],yn=(0,i.useState)(""),vn=(0,a.A)(yn,2),xn=vn[0],bn=vn[1],wn=(0,i.useState)(null),kn=(0,a.A)(wn,2),An=kn[0],jn=kn[1],Nn=(0,i.useState)({headerImageUrl:"",coverImageUrl:"",chatbotImageUrl:"",headerTitle:"",workspaceTheme:null}),Cn=(0,a.A)(Nn,2),Sn=Cn[0],En=Cn[1],In=(0,i.useState)(null),Dn=(0,a.A)(In,2),Pn=Dn[0],Tn=Dn[1],Rn=(0,i.useState)(null),On=(0,a.A)(Rn,2),Fn=On[0],Ln=On[1],_n=(0,i.useState)(null),Un=(0,a.A)(_n,2),Mn=Un[0],zn=Un[1],Bn=(0,i.useState)(null),Wn=(0,a.A)(Bn,2),Vn=Wn[0],Jn=Wn[1],qn=(0,i.useState)(!1),Hn=(0,a.A)(qn,2),Gn=Hn[0],Kn=Hn[1],Qn=(0,i.useState)(null),Yn=(0,a.A)(Qn,2),Zn=Yn[0],$n=Yn[1],Xn=(0,i.useState)(()=>(0,Oe.Sw)({})),er=(0,a.A)(Xn,2),tr=er[0],nr=er[1],rr=(0,i.useState)(!1),or=(0,a.A)(rr,2),ar=or[0],ir=or[1],sr=(0,i.useState)(!1),lr=(0,a.A)(sr,2),dr=lr[0],cr=lr[1],ur=(0,i.useRef)(null),mr=(0,i.useState)(()=>Ke(r,null===s||void 0===s?void 0:s.title)),pr=(0,a.A)(mr,2),gr=pr[0],hr=pr[1],fr=(0,i.useState)("auto"),yr=(0,a.A)(fr,2),vr=yr[0],xr=yr[1],br=(0,i.useState)(!1),wr=(0,a.A)(br,2),kr=wr[0],Ar=wr[1],jr=(0,i.useMemo)(()=>{if(!t||!Array.isArray(null===s||void 0===s?void 0:s.documents))return[];const e=String(t);return s.documents.filter(t=>Array.isArray(t.workspaceIds)&&t.workspaceIds.some(t=>String(t)===e))},[t,null===s||void 0===s?void 0:s.documents]),Nr=(0,i.useMemo)(()=>{if(!An)return jr.map(e=>e.id);const e=new Set(jr.map(e=>e.id));return An.filter(t=>e.has(t))},[An,jr]),Cr=(0,i.useMemo)(()=>{const e=new Set(Nr);return jr.filter(t=>!e.has(t.id)).map(e=>e.id)}
1,[Nr,jr]),Sr=(0,i.useMemo)(()=>Jt&&Array.isArray(null===s||void 0===s?void 0:s.documents)&&s.documents.find(e=>e.id===Jt)||null,[Jt,null===s||void 0===s?void 0:s.documents]),Er=(0,i.useMemo)(()=>{if(null===Sr||void 0===Sr||!Sr.editorJson)return!1;try{const e="string"===typeof Sr.editorJson?JSON.parse(Sr.editorJson):Sr.editorJson;return(0,Ue.oz)(e)}catch(e){return!1}},[Sr]);(0,i.useEffect)(()=>{xr((null===Sr||void 0===Sr?void 0:Sr.formWizardMode)||"auto")},[null===Sr||void 0===Sr?void 0:Sr.id,null===Sr||void 0===Sr?void 0:Sr.formWizardMode]);const Ir=(0,i.useCallback)(async e=>{if(Jt&&["auto","on","off"].includes(e)){xr(e),Ar(!0);try{const t=(0,ge.httpsCallable)((0,ge.getFunctions)(),"updateDocumentFormWizardMode");await t({documentId:Jt,formWizardMode:e}),Ie.Ay.success("Multi-step form setting saved")}catch(t){console.error("Failed to update formWizardMode:",t),Ie.Ay.error("Could not save multi-step form setting"),xr((null===Sr||void 0===Sr?void 0:Sr.formWizardMode)||"auto")}finally{Ar(!1)}}},[Jt,null===Sr||void 0===Sr?void 0:Sr.formWizardMode]),Dr=((0,i.useRef)(null),(0,i.useRef)(null)),Pr=(0,i.useRef)(null),Tr=(0,i.useRef)(null),Rr=(0,i.useRef)(null),Or=(0,he.xI)(),Fr=(0,B.aU)();(0,i.useEffect)(()=>{if(!c||!S)return Tn(null),void Ln(null);let e=!1;return(async()=>{try{var t,n;const r=await(0,Pe.getUserOrganizationData)(S);if(e)return;const o=null===r||void 0===r||null===(t=r.settings)||void 0===t||null===(n=t.branding)||void 0===n?void 0:n.logoUrl;Tn("string"===typeof o&&o.trim()?o.trim():null);const a=null===r||void 0===r?void 0:r.name;Ln("string"===typeof a&&a.trim()?a.trim():null)}catch(r){(0,W.gg)("Share modal: could not load org logo",r),e||(Tn(null),Ln(null))}})(),()=>{e=!0}},[c,S]),(0,i.useEffect)(()=>{if(!c)return zn(null),void Kn(!1);if(!S)return zn(null),Jn(null),void Kn(!0);let e=!1;return Kn(!1),(async()=>{try{var t,n,r;const o=(0,ge.getFunctions)(),a=(0,ge.httpsCallable)(o,"getCustomDomainSettings"),i=await a({organizationId:S});if(e)return;const s=(null===(t=i.data)||void 0===t?void 0:t.sharedDomain)||(null===(n=i.data)||void 0===n?void 0:n.domain),l=null===(r=i.data)||void 0===r?void 0:r.mascotDomain;null===s||void 0===s||!s.hostname||"active"!==s.status&&"pending_dns"!==s.status?zn(null):zn({hostname:s.hostname,status:s.status,purpose:s.purpose||"shared"}),null===l||void 0===l||!l.hostname||"active"!==l.status&&"pending_dns"!==l.status?Jn(null):Jn({hostname:l.hostname,status:l.status,purpose:l.purpose||"mascot"})}catch(o){e||(zn(null),Jn(null)),(0,W.gg)("Share modal: custom domain settings unavailable",(null===o||void 0===o?void 0:o.message)||o)}finally{e||Kn(!0)}})(),()=>{e=!0}},[c,S]);const Lr=(0,i.useMemo)(()=>(0,Be.XI)(Mn),[Mn]),_r=(0,i.useCallback)(function(e){let t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).mascotMode,n=void 0!==t&&t;return(0,ze.Xe)({linkId:e,mascotMode:n,customDomain:Mn,mascotDomain:Vn,origin:n?void 0:Lr})},[Lr,Mn,Vn]);(0,i.useEffect)(()=>{if(!c||!ie||!Gn)return;const e=_r(ie,{mascotMode:$t});e&&U(t=>t===e?t:e)},[c,ie,$t,_r,Gn]),(0,i.useEffect)(()=>{if(!c||!t)return $n(null),nr((0,Oe.Sw)({})),void ir(!1);let e=!1;return ir(!0),(async()=>{try{if(I){const n=(0,B.doc)(Fr,"externalAgents",I),r=await(0,B.getDoc)(n);if(e)return;if(r.exists()){const e=r.data();if(e.workspaceId===t)return $n(r.id),void nr((0,Oe.Sw)(e))}}const n=(0,B.P)((0,B.rJ)(Fr,"externalAgents"),(0,B._M)("workspaceId","==",t)),r=await(0,B.GG)(n);if(e)return;if(r.empty)$n(null),nr((0,Oe.Sw)({}));else{const e=r.docs.slice().sort((e,t)=>{const n=Ve(e.data()),r=Ve(t.data());return n!==r?n-r:e.id.localeCompare(t.id)})[0],t=e.data();$n(e.id),nr((0,Oe.Sw)(t))}}catch(n){(0,W.gg)("Share modal: externalAgents load failed",n),e||($n(null),nr((0,Oe.Sw)({})))}finally{e||ir(!1)}})(),()=>{e=!0}},[c,t,Fr,I]),(0,i.useEffect)(()=>()=>{ur.current&&clearTimeout(ur.current)},[]);const Ur=(0,i.useMemo)(()=>He(r,null===s||void 0===s?void 0:s.title),[r,null===s||void 0===s?void 0:s.title]),Mr=async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const n=nt.current,r=(async r=>{await n.catch(()=>{});const a=e.isPublic,i=void 0===a?K:a,s=e.expiryDate,l=void 0===s?ne:s,d=e.includeAgent,c=void 0===d?st:d,u=e.agentConfig,m=void 0===u?gr:u,p=e.emailNotifications,g=void 0===p?ut:p,h=e.emailOnOpen,f=void 0===h?ht:h,y=e.requireContactBeforeView,v=void 0===y?xt:y,x=e.commentsEnabled,b=void 0===x?At:x,w=e.shareAsReport,k=void 0===w?nn:w,A=e.reportIntroduction,j=void 0===A?un:A,C=e.reportCoverButtonColor,S=void 0===C?hn:C,E=e.sharedDocumentIds,I=void 0===E?An:E,D=e.linkLabel,P=void 0===D?xn:D,T=e.mascotMode,R=void 0===T?$t:T,F=Object.prototype.hasOwnProperty.call(e,"enabledViews")&&null!==(r=e.enabledViews)&&void 0!==r?r:Kt,L=Object.prototype.hasOwnProperty.call(e,"shareBranding")?e.shareBranding:void 0;try{const e=Or.currentUser;if(!e)return void Ye("You must be signed in to create a shareable link.");const n=t;if(!n)return void Ye("Missing workspaceId.");J(!0);const r=await e.getIdToken(),a=l?new Date(l).toISOString():null;let s=ie||void 0;N&&ie?(0,W.gg)("\ud83d\udcc4 Document-level share: Using linkId only if it matches documentId context"):!N&&ie&&(0,W.gg)("\ud83d\udcda Workspace-level share: Using linkId only if it matches workspace context");const d=(0,o.A)((0,o.A)((0,o.A)({isPublic:i,expiryDate:a,agentConfig:(0,o.A)((0,o.A)({},m),{},{enabled:!!c}
1),emailNotifications:g,emailOnOpen:f,requireContactBeforeView:v,commentsEnabled:b,linkId:s,enabledViews:F,shareAsReport:k,reportIntroduction:(j||"").trim(),reportCoverButtonColor:(0,De.qw)(S),hideTimeEntryTimestamps:!(0,Me.a8)()},Jt&&{documentId:Jt}),O&&{mascotMode:!0===R}),!Jt&&{sharedDocumentIds:(()=>{if(!Array.isArray(I)||0===I.length)return null;const e=new Set(jr.map(e=>e.id)),t=I.filter(t=>e.has(t));return t.length>0?t:null})(),linkLabel:(P||"").trim()});void 0!==L&&(d.shareBranding={headerImageUrl:((null===(z=L)||void 0===z?void 0:z.headerImageUrl)||"").trim()||null,coverImageUrl:((null===z||void 0===z?void 0:z.coverImageUrl)||"").trim()||null,chatbotImageUrl:((null===z||void 0===z?void 0:z.chatbotImageUrl)||"").trim()||null,headerTitle:((null===z||void 0===z?void 0:z.headerTitle)||"").trim()||null,workspaceTheme:(null==(null===z||void 0===z?void 0:z.workspaceTheme)||"object"!==typeof z.workspaceTheme||Array.isArray(z.workspaceTheme)?null:z.workspaceTheme)||null}),(0,W.gg)("\ud83d\udce4 Sending to backend:",{linkId:s||"NEW (no linkId in state!)",documentId:Jt||"none (workspace-level)",shareScope:zt,isPublic:i,workspaceId:n,enabledViews:d.enabledViews,shareAsReport:d.shareAsReport,reportIntroductionLen:(d.reportIntroduction||"").length,fullRequestBody:d});const u=await fetch("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/createShareableLink?knowledgeBaseId=".concat(n),{method:"POST",headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(r)},body:JSON.stringify(d)});if(!u.ok){const e=await u.text();console.error("API Error Response:",e);let t="";try{var M;t=(null===(M=JSON.parse(e))||void 0===M?void 0:M.error)||""}catch(B){}throw new Error(t||"Failed to generate link: "+u.status)}const p=await u.json();if((0,W.gg)("\ud83d\udce5 Response from backend:",{linkId:p.linkId,isPublic:p.isPublic,shareableLink:p.shareableLink,enabledViews:p.enabledViews,shareAsReport:p.shareAsReport,reportIntroductionLen:(p.reportIntroduction||"").length,reportCoverButtonColor:p.reportCoverButtonColor,wasUpdate:ie?"YES (updated existing)":"NO (created new)"}),fn((0,De.qw)(p.reportCoverButtonColor)),void 0!==p.shareBranding&&En(Fe(p.shareBranding)),p.linkId){const e=p.shareableLink||_r(p.linkId,{mascotMode:!0===p.mascotMode});e&&e!==_&&U(e),p.linkId!==ie&&se(p.linkId)}return void 0!==p.mascotMode&&Xt(!0===p.mascotMode),void 0!==p.isPublic&&p.isPublic!==K&&((0,W.gg)("\ud83d\udd04 Updating isPublic from backend response:",p.isPublic),Q(p.isPublic)),"traditional"!==p.enabledViews&&"search"!==p.enabledViews&&"both"!==p.enabledViews||Qt(p.enabledViews),p}catch(Le){console.error("Error generating/updating link:",Le);const t=Le.message||"Failed to generate link";throw!rt.current?(Ye(t),t.includes("permission")||t.includes("Permission")?Ie.Ay.error("Missing or insufficient permissions. Please check your access to this workspace.",{duration:5e3}):Ie.Ay.error("Failed to generate link: ".concat(t),{duration:4e3}
1)):(0,W.gg)("Background link generation failed (this is normal):",t),Le}finally{J(!1)}var z})();return nt.current=r,await r},zr=async e=>{(0,W.gg)("Toggle clicked:",e,"Current link:",_),Q(e);const t={isPublic:e,expiryDate:ne,includeAgent:st,agentConfig:gr};if(_&&!V)try{const e=await Mr(t);(0,W.gg)("Link updated successfully:",e.shareableLink)}catch(Le){console.error("Error updating link visibility:",Le);const n=Le.message||"Failed to update link visibility";Q(!e),n.includes("permission")||n.includes("Permission")?Ie.Ay.error("Missing or insufficient permissions. Please check your access to this workspace.",{duration:5e3}):Ie.Ay.error("Failed to update link visibility: ".concat(n),{duration:4e3})}else if(!_&&!V)try{await Mr(t)}catch(Le){console.error("Error generating new link:",Le);const n=Le.message||"Failed to generate link";Q(!e),n.includes("permission")||n.includes("Permission")?Ie.Ay.error("Missing or insufficient permissions. Please check your access to this workspace.",{duration:5e3}):Ie.Ay.error("Failed to generate link: ".concat(n),{duration:4e3})}},Br=(0,i.useCallback)(async e=>{if(!Zn)return;const t=!(!e.liveRequestsEmbedEnabled&&!e.liveRequestsShareLinkEnabled);if(t){if(0===(e.liveRequestTeamMembers||[]).filter(e=>(e.name||"").trim().length>0).length)return void Ie.Ay.error("Add at least one team member with a name when Live Chat is enabled.")}try{const n=!!e.liveRequestsShareLinkEnabled,r={liveRequestsEmbedEnabled:!!e.liveRequestsEmbedEnabled,liveRequestsShareLinkEnabled:!!e.liveRequestsShareLinkEnabled,liveRequestsEnabled:!(!e.liveRequestsEmbedEnabled&&!e.liveRequestsShareLinkEnabled),liveRequestNotifyChannelsShare:t&&e.liveRequestNotifyChannels||[],liveRequestAppStoreUrl:t?Te.w:"",liveRequestTeamMembersShare:t&&e.liveRequestTeamMembers||[]};n&&(r.liveRequestCapsuleLabelShare=e.liveRequestCapsuleLabel||"Speak to our team",r.liveRequestWelcomeMessageShare=e.liveRequestWelcomeMessage||"",r.liveRequestOfflineMessageShare=e.liveRequestOfflineMessage||Oe.jf,r.liveRequestAutoResolveEnabledShare=!1!==e.liveRequestAutoResolveEnabled,r.liveRequestAutoResolveMinutesShare=e.liveRequestAutoResolveMinutes||3),await(0,B.mZ)((0,B.doc)(Fr,"externalAgents",Zn),r)}catch(n){(0,W.gg)("Share modal: persist live chat failed",n),Ie.Ay.error("Could not save Live Chat settings.")}},[Zn,Fr]),Wr=(0,i.useCallback)(e=>{nr(t=>{const n=(0,o.A)((0,o.A)({},t),e);return ur.current&&clearTimeout(ur.current),ur.current=setTimeout(()=>{Br(n)},450),n})},[Br]),Vr=(0,i.useCallback)(async()=>{if(!t||!Or.currentUser)return void Ie.Ay.error("You must be signed in to set up Live Chat.");const e=qe(r,null===s||void 0===s?void 0:s.title);cr(!0);try{const n={workspaceId:t,name:"".concat(e," Chatbot"),description:"AI agent for ".concat(e),theme:"default",customColor:"#3B82F6",position:"bottom-right",size:"medium",welcomeMessage:gr.welcomeMessage||"Hello! How can I help you today?",placeholder:"Ask me anything...",branding:!0,showKnowledgeBaseContent:!1,autoOpenOnScroll:!1,notificationsEnabled:!1,notificationEmails:Or.currentUser.email||"",leadCaptureEnabled:!0,leadCaptureMode:"no_answer_only",liveRequestsEmbedEnabled:!1,liveRequestsShareLinkEnabled:!1,liveRequestsEnabled:!1,liveRequestAppStoreUrl:"",liveRequestCapsuleLabelShare:"Speak to our team",liveRequestWelcomeMessageShare:"",liveRequestOfflineMessageShare:Oe.jf,liveRequestAutoResolveEnabledShare:!0,liveRequestAutoResolveMinutesShare:3,createdBy:Or.currentUser.uid||"unknown",createdAt:(0,B.O5)(),updatedAt:(0,B.O5)()},r=await(0,B.gS)((0,B.rJ)(Fr,"externalAgents"),n);$n(r.id),nr((0,Oe.Sw)(n)),Ie.Ay.success("Workspace assistant created. Configure Live Chat below.")}catch(n){(0,W.gg)("Share modal: create externalAgents failed",n),Ie.Ay.error(n.message||"Could not create workspace assistant.")}finally{cr(!1)}},[t,r,null===s||void 0===s?void 0:s.title,gr.welcomeMessage,Or,Fr]),Jr=(0,i.useCallback)(async(e,n)=>{if(!n||!Or.currentUser)return;const r=t||"unknown",a=n.name.replace(/[^a-zA-Z0-9._-]/g,"_"),i="kb_uploads/".concat(Or.currentUser.uid,"/liveChatTeam/").concat(r,"_").concat(e,"_").concat(Date.now(),"_").concat(a),s=(0,Ee.KR)(G.IG,i);await(0,Ee.D)(s,n,{contentType:n.type||"image/jpeg"});const l=await(0,Ee.qk)(s);nr(t=>{const n=(0,o.A)((0,o.A)({},t),{},{liveRequestTeamMembers:(t.liveRequestTeamMembers||[]).map(t=>
1t.id===e?(0,o.A)((0,o.A)({},t),{},{avatarUrl:l}):t)});return ur.current&&clearTimeout(ur.current),ur.current=setTimeout(()=>{Br(n)},450),n})},[t,Or,Br]),qr=e=>{hr(e)},Hr=async e=>{const t=Kt;if(Qt(e),_&&!V)try{await Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:ut,commentsEnabled:At,enabledViews:e})}catch(Le){console.error("Error updating enabled views:",Le),Qt(t);const n=Le.message||"Failed to update view settings";n.includes("permission")||n.includes("Permission")?Ie.Ay.error("Missing or insufficient permissions. Please check your access to this workspace.",{duration:5e3}):Ie.Ay.error("Failed to update view settings: ".concat(n),{duration:4e3})}},Gr=async()=>{if(ie)try{await Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:ut,commentsEnabled:At})}catch(e){console.error("Error persisting agent config:",e)}};(0,i.useEffect)(()=>{if(ie&&ne)return tt.current&&clearTimeout(tt.current),tt.current=setTimeout(async()=>{try{await Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,commentsEnabled:At})}catch(Le){console.error("Error debounced update:",Le)}},600),()=>clearTimeout(tt.current)},[ne,ie]),(0,i.useEffect)(()=>{(async()=>{if(c){ue(!0),Ye(null);try{if(x){var e;(0,W.gg)("Using link from props:",x),(0,W.gg)("\ud83d\udd0d currentLink report fields:",{shareAsReport:x.shareAsReport,reportIntroductionLen:(x.reportIntroduction||"").length,enabledViews:x.enabledViews});const t=!!A||!1!==x.isPublic,n=(null===(e=x.agentConfig)||void 0===e?void 0:e.enabled)||!1,a=Qe(x.agentConfig,r,null===s||void 0===s?void 0:s.title),i=x.enabledViews||"both",l=!1!==x.emailNotifications,d=!0===x.emailOnOpen,c=!0===x.requireContactBeforeView,u=!0===x.commentsEnabled,m=x.expiryDate?new Date(x.expiryDate).toISOString().split("T")[0]:"",p=!0===x.shareAsReport,g=x.reportIntroduction||"",h=(0,De.qw)(x.reportCoverButtonColor),f=!0===x.mascotMode;U(_r(x.linkId,{mascotMode:f})),Xt(f),Q(t),se(x.linkId||""),mt(l),ft(d),bt(c),jt(u),lt(n),hr(e=>(0,o.A)((0,o.A)({},e),a)),Qt(i),re(m),rn(p),mn(g),fn(h);const y=x.linkLabel||"",v=x.sharedDocumentIds||null,b=Fe(x.shareBranding);return bn(y),jn(v),En(b),ot.current={isPublic:t,includeAgent:n,emailNotifications:l,emailOnOpen:d,requireContactBeforeView:c,commentsEnabled:u,enabledViews:i,expiryDate:m,linkId:x.linkId||"",agentConfig:n?a:null,shareAsReport:p,reportIntroduction:g,reportCoverButtonColor:h,sharedDocumentIds:v,linkLabel:y,shareBranding:b,mascotMode:f},void ue(!1)}if(!x&&!Jt)return U(""),se(""),bn(""),jn(null),En({headerImageUrl:"",coverImageUrl:"",chatbotImageUrl:"",headerTitle:"",workspaceTheme:null}),ot.current=null,Et(!1),void ue(!1);const a=t||(null===s||void 0===s?void 0:s.id);if(!a)return(0,W.gg)("No workspaceId available"),void ue(!1);(0,W.gg)("Fetching link from database for:",a);const i=(0,B.rJ)(Fr,"shareableLinks");let l;l=Jt?(0,B.P)(i,(0,B._M)("workspaceId","==",a),(0,B._M)("documentId","==",Jt),(0,B.AB)(1)):(0,B.P)(i,(0,B._M)("workspaceId","==",a));const d=await(0,B.GG)(l);(0,W.gg)("Query executed for workspaceId:",a),(0,W.gg)("Documents found:",d.size);let c=null;if(!d.empty)if(Jt)c=d.docs[0],c.data().documentId||((0,W.gg)("\u26a0\ufe0f Query returned workspace-level link when documentId was expected. Ignoring."),c=null);else{const e=d.docs.filter(e=>!e.data().documentId).sort((e,t)=>{var n,r,o,a;const i=(null===(n=e.data().updatedAt)||void 0===n||null===(r=n.toMillis)||void 0===r?void 0:r.call(n))||(e.data().updatedAt instanceof Date?e.data().updatedAt.getTime():0);return((null===(o=t.data().updatedAt)||void 0===o||null===(a=o.toMillis)||void 0===a?void 0:a.call(o))||(t.data().updatedAt instanceof Date?t.data().updatedAt.getTime():0))-i});e.length>0&&(c=e[0])}if(c){var n;const e=c.data();(0,W.gg)("Found existing link:",{linkId:e.linkId,documentId:e.documentId||"none (workspace-level)",isPublic:e.isPublic,requestedDocumentId:N||"none"});const t=!0===e.mascotMode,a=_r(e.linkId,{mascotMode:t}),i=!!A||!1!==e.isPublic,l=(null===(n=e.agentConfig)||void 0===n?void 0:n.enabled)||!1,d=Qe(e.agentConfig,r,null===s||void 0===s?void 0:s.title),u=e.enabledViews||"both",m=!1!==e.emailNotifications,p=!0===e.emailOnOpen,g=!0===e.requireContactBeforeView,h=!0===e.commentsEnabled,f=e.expiryDate?new Date(e.expiryDate).toISOString().split("T")[0]:"",y=!0===e.shareAsReport,v=e.reportIntroduction||"",x=(0,De.qw)(e.reportCoverButtonColor);U(a),Xt(t),Q(i),se(e.linkId||""),mt(m),ft(p),bt(g),jt(h),lt(l),hr
1(e=>(0,o.A)((0,o.A)({},e),d)),Qt(u),re(f),rn(y),mn(v),fn(x);const b=e.linkLabel||"",w=e.sharedDocumentIds||null,k=Fe(e.shareBranding);bn(b),jn(w),En(k),ot.current={isPublic:i,includeAgent:l,emailNotifications:m,emailOnOpen:p,requireContactBeforeView:g,commentsEnabled:h,enabledViews:u,expiryDate:f,linkId:e.linkId||"",agentConfig:l?d:null,shareAsReport:y,reportIntroduction:v,reportCoverButtonColor:x,sharedDocumentIds:w,linkLabel:b,shareBranding:k,mascotMode:t}}else(0,W.gg)("No existing link found for:",{workspaceId:a,documentId:Jt||"none (workspace-level)",shareScope:zt}),U(""),se(""),bn(""),jn(null),En({headerImageUrl:"",coverImageUrl:"",chatbotImageUrl:"",headerTitle:"",workspaceTheme:null}),Qt("both"),ot.current=null,Et(!1)}catch(a){console.error("Error fetching existing link:",a);const e=a.message||"Unknown error";e.includes("permission")||e.includes("Permission")?((0,W.gg)("Permission error during link fetch (this is normal if no link exists):",e),Ye(null)):Ye(e)}finally{ue(!1)}}else Ye(null)})()},[c,t,x,Fr,Jt,zt]),(0,i.useEffect)(()=>{const e=setTimeout(async()=>{if(!c||ce||_||V||ie||rt.current){if(c&&!ce&&(_||ie)&&((0,W.gg)("\u2139\ufe0f Existing link found, skipping auto-generation"),A&&ie&&!rt.current)){(0,W.gg)("\ud83d\udd04 Updating existing link to public..."),rt.current=!0;try{await Mr({isPublic:!0,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:ut,commentsEnabled:At,enabledViews:Kt,shareAsReport:nn,reportIntroduction:un||"",reportCoverButtonColor:hn}),(0,W.gg)("\u2705 Link updated to public")}catch(Le){console.error("\u274c Error updating link to public:",Le),rt.current=!1}}}else{(0,W.gg)("\ud83d\udd04 No existing link found, auto-generating..."),rt.current=!0;try{await Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:ut,commentsEnabled:At,enabledViews:Kt,mascotMode:$t,shareAsReport:nn,reportIntroduction:un||"",reportCoverButtonColor:hn}),(0,W.gg)("\u2705 Link auto-generated successfully")}catch(Le){console.error("\u274c Error auto-generating link:",Le),rt.current=!1}}},800);return()=>clearTimeout(e)},[c,ce,A,Jt,zt]),(0,i.useEffect)(()=>{A&&c&&((0,W.gg)("\ud83d\udd04 Force setting isPublic to true"),Q(!0))},[A,c]),(0,i.useEffect)(()=>{!_||!c||Xe||ce||V||((0,W.gg)("Auto-copying link to clipboard:",_),navigator.clipboard.writeText(_).then(()=>{(0,W.gg)("Link automatically copied to clipboard"),X(!0),et(!0),setTimeout(()=>X(!1),2e3)}).catch(e=>{console.error("Failed to auto-copy the link:",e)}))},[_,c,ce,Xe,V]),(0,i.useEffect)(()=>{c||(et(!1),ln("link"))},[c]);const Kr=async()=>{try{await Mr()}catch(Le){console.error("Error generating initial link:",Le)}};(0,i.useEffect)(()=>{c||(rt.current=!1)},[c]),(0,i.useEffect)(()=>{rt.current=!1},[t]),(0,i.useEffect)(()=>{c&&(N?(Bt("document"),qt(N)):(Bt("workspace"),qt(null)))},[c,N]),(0,i.useEffect)(()=>{qt("document"===zt&&N?N:null)},[zt,N]);const Qr=(0,i.useRef)(Jt);(0,i.useEffect)(()=>{c&&ie&&Qr.current!==Jt&&((0,W.gg)("\ud83d\udd04 Share scope changed (was:",Qr.current?"document":"workspace","now:",Jt?"document":"workspace","), clearing linkId"),se(""),U(""),rt.current=!1),Qr.current=Jt},[Jt,c,ie]);const Yr=(0,i.useMemo)(()=>{var e,t,n;const r=null!==(e=Sn.headerImageUrl)&&void 0!==e?e:"",o=null!==(t=Sn.coverImageUrl)&&void 0!==t?t:"",a=null!==(n=Sn.chatbotImageUrl)&&void 0!==n?n:"",i=r===o&&o===a;return{allEqual:i,unifiedPreviewUrl:i?r.trim():""}},[Sn]),Zr=(0,i.useMemo)(()=>(Sn.headerTitle||"").trim()?Sn.headerTitle:Fn||"",[Sn.headerTitle,Fn]),$r=(0,i.useCallback)(()=>{var e;if(!ot.current)return void Et(!!_);const t=ot.current,n=e=>null==e?"all":JSON.stringify(e),r=t.isPublic!==K||t.includeAgent!==st||t.emailNotifications!==ut||Boolean(t.emailOnOpen)!==Boolean(ht)||Boolean(t.requireContactBeforeView)!==Boolean(xt)||t.commentsEnabled!==At||t.enabledViews!==Kt||t.mascotMode!==$t||t.expiryDate!==ne||t.linkId!==ie||t.shareAsReport!==nn||t.reportIntroduction!==un||t.reportCoverButtonColor!==hn||JSON.stringify(t.agentConfig)!==JSON.stringify(st?gr:null)||n(t.sharedDocumentIds)!==n(An)||(t.linkLabel||"")!==(xn||"")||JSON.stringify(null!==(e=t.shareBranding)&&void 0!==e?e:{headerImageUrl:"",coverImageUrl:"",chatbotImageUrl:"",headerTitle:"",workspaceTheme:null})!==JSON.stringify(Sn);Et(r)},[K,st,ut,ht,xt,At,Kt,$t,ne,ie,gr,_,nn,un,hn,An,xn,Sn]);(0,i.useEffect)(()=>{$r()},[$r]),(0,i.useEffect)(()=>{St&&(Tt(!1),Rt.current&&(clearTimeout(Rt.current),Rt.current=null))},[St]),(0,i.useEffect)(()=>()=>{Rt.current&&clearTimeout(Rt.current)},[]),(0,i.useEffect)(()=>{_&&ie&&!ot.current&&rt.current&&(ot.current={isPublic:K,includeAgent:st,emailNotifications:ut,emailOnOpen:ht,requireContactBeforeView:xt,commentsEnabled:At,enabledViews:Kt,expiryDate:ne,linkId:ie,agentConfig:st?gr:null,shareAsReport:nn,reportIntroduction:un,reportCoverButtonColor:hn,sharedDocumentIds:An,linkLabel:xn||"",shareBranding:(0,o.A)({},Sn),mascotMode:$t},Et(!1))},[_,ie,K,st,ut,ht,xt,At,Kt,$t,ne,gr,nn,un,hn,An,xn,Sn]);
1const Xr=Lt?"Saving\u2026":St?"Save changes":_?"Close":"Save Settings";return c?((0,W.gg)("Modal should be visible now"),(0,We.jsx)("div",{className:"fixed inset-0 z-[10000] overflow-y-auto","aria-modal":"true",role:"dialog",children:(0,We.jsxs)("div",{className:"flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0",children:[(0,We.jsx)("div",{className:"fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75",onClick:u,"aria-hidden":"true"}),(0,We.jsxs)("div",{className:"inline-block overflow-hidden text-left align-bottom transition-all transform bg-white rounded-lg shadow-xl sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full",children:[(0,We.jsx)("div",{className:"px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4",children:(0,We.jsx)("div",{className:"sm:flex sm:items-start",children:(0,We.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsx)("h3",{className:"text-lg font-medium leading-6 text-gray-900",children:"document"===zt?"Share this document":"Share this workspace"}),St&&(0,We.jsxs)("div",{className:"flex items-center text-sm text-amber-600",children:[(0,We.jsx)("span",{className:"w-2 h-2 bg-amber-500 rounded-full mr-2 animate-pulse","aria-hidden":!0}),"Save changes"]}),!St&&Pt&&(0,We.jsxs)("div",{className:"flex items-center text-sm text-emerald-600",role:"status","aria-live":"polite",children:[(0,We.jsx)(d.A,{className:"w-4 h-4 mr-1.5 shrink-0",strokeWidth:2.5,"aria-hidden":!0}),"Changes saved"]})]}),Le&&(0,We.jsx)("div",{className:"mt-2 p-3 bg-red-50 rounded-md",children:(0,We.jsx)("p",{className:"text-sm text-red-700",children:Le})}),(0,We.jsx)("div",{className:"mt-4 border-b border-gray-200",children:(0,We.jsx)("nav",{className:"flex gap-1 -mb-px","aria-label":"Tabs",children:[{id:"link",label:"Link",icon:ye.A},{id:"display",label:"Display",icon:ve.A},{id:"assistant",label:"AI Assistant",icon:f.A},{id:"comments",label:"Comments",icon:xe.A},{id:"analytics",label:"Analytics",icon:be.A}].map(e=>{let t=e.id,n=e.label,r=e.icon;return(0,We.jsxs)("button",{type:"button",onClick:()=>ln(t),className:"flex items-center gap-2 px-4 py-3 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ".concat(sn===t?"border-blue-500 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"),children:[(0,We.jsx)(r,{className:"w-4 h-4"}),n]},t)})})}),_&&(0,We.jsxs)("div",{className:"mt-3 mr-2 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-gray-200 bg-gray-50 px-3 py-2.5",children:[(0,We.jsxs)("p",{className:"text-sm text-gray-600 m-0",children:["Open how your visitors will see this ","document"===zt?"document":"workspace","."]}),(0,We.jsxs)("button",{type:"button",onClick:()=>window.open(_,"_blank","noopener,noreferrer"),className:"inline-flex shrink-0 items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-gray-800 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:[(0,We.jsx)(ye.A,{className:"w-4 h-4"}),"Preview Link"]})]}),(0,We.jsxs)("div",{className:"mt-4 space-y-6 mr-2 max-h-[60vh] overflow-y-auto",children:["link"===sn&&(0,We.jsxs)(We.Fragment,{children:[N&&!P&&(0,We.jsxs)("div",{className:"border-b border-gray-200 pb-4",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"What would you like to share?"}),(0,We.jsxs)("div",{className:"flex gap-3",children:[(0,We.jsxs)("button",{type:"button",onClick:()=>{Bt("document"),se(""),U("")},disabled:V,className:"flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ".concat("document"===zt?"border-blue-500 bg-blue-50 text-blue-700":"border-gray-200 bg-white text-gray-700 hover:border-gray-300"," ").concat(V?"opacity-50 cursor-not-allowed":"cursor-pointer"),children:[(0,We.jsx)(R.A,{className:"w-5 h-5"}),(0,We.jsxs)("div",{className:"text-left",children:[(0,We.jsx)("div",{className:"font-medium",children:"This Document"}),(0,We.jsx)("div",{className:"text-xs opacity-75",children:"Share only this document"})]})]}),(0,We.jsxs)("button",{type:"button",onClick:()=>{Bt("workspace"),se(""),U("")},disabled:V,className:"flex-1 flex items-center justify-center gap-2 px-4 py-3 rounded-lg border-2 transition-all ".concat("workspace"===zt?"border-blue-500 bg-blue-50 text-blue-700":"border-gray-200 bg-white text-gray-700 hover:border-gray-300"," ").concat(V?"opacity-50 cursor-not-allowed":"cursor-pointer"),children:[(0,We.jsx)(g.A,{className:"w-5 h-5"}),(0,We.jsxs)("div",{className:"text-left",children:[(0,We.jsx)("div",{className:"font-medium",children:"Entire Worksp
1ace"}),(0,We.jsx)("div",{className:"text-xs opacity-75",children:"Share all documents"})]})]})]})]}),!N&&(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{htmlFor:"linkLabel",className:"block text-sm font-medium text-gray-700 mb-1",children:"Link Name"}),(0,We.jsx)("input",{type:"text",id:"linkLabel",value:xn,onChange:e=>bn(e.target.value),placeholder:"e.g. Public docs, Client portal\u2026",className:"w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500 text-sm"})]}),!N&&jr.length>0&&(0,We.jsxs)("div",{children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700",children:"Documents"}),Cr.length>0&&(0,We.jsxs)("button",{type:"button",onClick:()=>jn(null),className:"inline-flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 font-medium",children:[(0,We.jsx)(we.A,{className:"w-3 h-3"}),"Reset"]})]}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mb-2",children:Cr.length>0?"Showing ".concat(Nr.length," of ").concat(jr.length," documents"):"All ".concat(jr.length," documents included")}),(0,We.jsxs)("div",{className:"border border-gray-200 rounded-md max-h-[220px] overflow-y-auto",children:[Nr.map((e,t)=>{const n=jr.find(t=>t.id===e);return n?(0,We.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 hover:bg-gray-50 border-b border-gray-100 last:border-b-0",children:[(0,We.jsx)("input",{type:"checkbox",checked:!0,onChange:()=>{const t=Nr.filter(t=>t!==e);jn(t.length>0?t:null)},className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,We.jsx)("span",{className:"flex-1 text-sm text-gray-700 truncate",children:(0,_e.Od)(n,"Untitled")}),(0,We.jsxs)("div",{className:"flex items-center gap-0.5 flex-shrink-0",children:[(0,We.jsx)("button",{type:"button",disabled:0===t,onClick:()=>{const e=[...Nr];var n=[e[t],e[t-1]];e[t-1]=n[0],e[t]=n[1],jn(e)},className:"p-0.5 text-gray-400 hover:text-gray-600 disabled:opacity-20",title:"Move up",children:(0,We.jsx)(ke.A,{className:"w-3.5 h-3.5"})}),(0,We.jsx)("button",{type:"button",disabled:t===Nr.length-1,onClick:()=>{const e=[...Nr];var n=[e[t+1],e[t]];e[t]=n[0],e[t+1]=n[1],jn(e)},className:"p-0.5 text-gray-400 hover:text-gray-600 disabled:opacity-20",title:"Move down",children:(0,We.jsx)(y.A,{className:"w-3.5 h-3.5"})})]})]},e):null}),Cr.map(e=>{const t=jr.find(t=>t.id===e);return t?(0,We.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 hover:bg-gray-50 border-b border-gray-100 last:border-b-0 opacity-50",children:[(0,We.jsx)("input",{type:"checkbox",checked:!1,onChange:()=>{jn([...Nr,e])},className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,We.jsx)("span",{className:"flex-1 text-sm text-gray-400 truncate",children:(0,_e.Od)(t,"Untitled")})]},e):null})]})]}),"document"===zt&&Er&&(0,We.jsxs)("div",{className:"rounded-lg border border-gray-200 p-4 space-y-2",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Multi-step form for clients"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Show one section at a time with a single Finish submit instead of multiple Submit buttons."})]}),(0,We.jsx)("div",{className:"flex flex-wrap gap-2",children:["auto","on","off"].map(e=>(0,We.jsx)("button",{type:"button",disabled:kr,onClick:()=>Ir(e),className:"px-3 py-1.5 text-xs font-medium rounded-md border capitalize ".concat(vr===e?"bg-blue-50 text-blue-700 border-blue-200":"text-gray-600 border-gray-200 hover:bg-gray-50"," disabled:opacity-50"),children:"auto"===e?"Auto":"on"===e?"On":"Off"},e))})]}),(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Access Control"}),(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsxs)("button",{type:"button",onClick:()=>zr(!0),disabled:V,className:"flex items-center mr-3 px-3 py-2 text-sm font-medium rounded-md ".concat(K?"bg-blue-50 text-blue-700 border border-blue-200":"text-gray-500 hover:bg-gray-50 border border-gray-200"," ").concat(V?"opacity-50 cursor-not-allowed":""),children:[(0,We.jsx)(l.A,{size:16,className:"mr-1"}),(0,We.jsx)("span",{children:"Public"}),V&&K&&(0,We.jsx)(Se.y$,{size:"sm",className:"ml-1 text-blue-600"})]}),(0,We.jsxs)("button",{type:"button",onClick:()=>zr(!1),disabled:V,className:"flex items-center px-3 py-2 mr-2 text-sm font-medium rounded-md ".concat(K?"text-gray-500 hover:bg-gray-50 border border-gray-200":"bg-blue-50 text-blue-700 border border-blue-200"," ").concat(V?"opacity-50 cursor-not-allowed":""),children:[(0,We.jsx)(b.A,{size:16,className:"mr-1"}),(0,We.jsx)("span",{children:"Private"}),V&&!K&&(0,We.jsx)(Se.y$,{size:"sm",className:"ml-1 text-blue-600"})]})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{htmlFor:"expiryDate",className:"block text-sm font-medium text-gray-700 mb-1",children:"Link Expiry (Optional)"}),(0,We.jsx)("input",{type:"date",id:"expiryDate",value:ne,onChange:e=>{return t=e.target.value,void re(t);var t},min:(new Date).toISOString().split("T")[0],className:"w-full p-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500 ".concat(V?"opacity-50 cursor-not-allowed":"")}),(0,We.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"Leave blank for a link that doesn't expire"})]}),(0,We.jsxs)("div",{children:[(0,We.jsxs)("label",{htmlFor:"shareLink",className:"block text-sm font-medium text-gray-700 mb-1",children:["Shareable Link ",_&&$&&(0,We.jsx)("span",{className:"ml-2 text-xs text-green-600",children:"(Copied to clipboard!)"})]}),(0,We.jsxs)("div",{className:"flex",children:[(0,We.jsx)("input",{type:"text",id:"shareLink",value:_,readOnly:!0,className:"flex-1 p-2 border border-r-0 border-gray-300 rounded-l-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"}),(0,We.jsx)("button",{onClick:()=>{navigator.clipboard.writeText(_),X(!0),setTimeout(()=>X(!1),2e3)},disabled:!_,className:"inline-flex items-center px-3 py-2 border border-gray-300 bg-gray-50 rounded-r-md hover:bg-gray-100 ".concat(_?"":"op
1acity-50 cursor-not-allowed"),title:"Copy to clipboard",children:$?(0,We.jsx)(d.A,{className:"w-5 h-5 text-green-500"}):(0,We.jsx)(w.A,{className:"w-5 h-5 text-gray-500"})})]}),!_&&(0,We.jsxs)("button",{onClick:Kr,disabled:V,className:"mt-2 inline-flex items-center px-3 py-2 text-sm font-medium text-blue-700 bg-blue-50 border border-blue-200 rounded-md hover:bg-blue-100 ".concat(V?"opacity-50 cursor-not-allowed":""),children:[(0,We.jsx)(ye.A,{className:"w-4 h-4 mr-1"}),V?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Se.y$,{size:"sm",className:"mr-1 text-blue-600"}),"Generating..."]}):"Generate Link"]}),(null===Mn||void 0===Mn?void 0:Mn.hostname)&&_&&!$t&&(0,We.jsx)("div",{className:"mt-3 rounded-md border border-blue-100 bg-blue-50 px-3 py-2.5",children:(0,We.jsx)("p",{className:"text-xs text-blue-900 m-0",children:"active"===Mn.status?(0,We.jsxs)(We.Fragment,{children:["Using your custom domain ",(0,We.jsx)("strong",{children:Mn.hostname})," for document share links."]}):(0,We.jsxs)(We.Fragment,{children:["Custom domain ",(0,We.jsx)("strong",{children:Mn.hostname})," is pending DNS \u2014 links will use it once verified."]})})})]})]}),"comments"===sn&&(0,We.jsx)(We.Fragment,{children:(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsx)(xe.A,{className:"w-5 h-5 text-blue-600 mr-2"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Allow Comments"}),(0,We.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5",children:["Enable visitors to comment on and highlight text in ","document"===zt?"this document":"documents"]})]})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer",children:[(0,We.jsx)("input",{type:"checkbox",checked:At,onChange:e=>{jt(e.target.checked),_&&Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:ut,commentsEnabled:e.target.checked})},disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]})}),"display"===sn&&(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"mb-6 flex items-center justify-between pb-6 border-b border-gray-200",children:[(0,We.jsxs)("div",{className:"flex items-start gap-2",children:[(0,We.jsx)(Ae.A,{className:"w-5 h-5 text-blue-600 shrink-0 mt-0.5"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-900",children:"Require contact info"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Visitors must enter first name, last name, and email before viewing document content (public links only)"})]})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer shrink-0 ml-4",children:[(0,We.jsx)("input",{type:"checkbox",checked:xt,onChange:async e=>{const t=e.target.checked;if(bt(t),_)try{await Mr({requireContactBeforeView:t}),ot.current&&(ot.current=(0,o.A)((0,o.A)({},ot.current),{},{requireContactBeforeView:t})),setTimeout(()=>{$r()},0)}catch(n){}},disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),(0,We.jsxs)("div",{className:"mb-6 space-y-2 pb-6 border-b border-gray-200",children:[(0,We.jsxs)("div",{className:"flex items-start gap-2",children:[(0,We.jsx)(je.A,{className:"w-5 h-5 text-blue-600 shrink-0 mt-0.5"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-900",children:"Header title"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Shown next to the logo on the public page. Defaults to your organization name."})]})]}),(0,We.jsx)("input",{type:"text",value:Zr,onChange:e=>En(t=>(0,o.A)((0,o.A)({},t),{},{headerTitle:e.target.value})),onBlur:e=>
1{const t=e.target.value.trim(),n=(Fn||"").trim(),r=t&&t!==n?t:"";En(e=>{const t=(0,o.A)((0,o.A)({},e),{},{headerTitle:r});return _&&!V&&queueMicrotask(()=>Mr({shareBranding:t})),t})},disabled:V,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),(0,We.jsxs)("div",{className:"mb-8 space-y-5 pb-6 border-b border-gray-200",children:[(0,We.jsxs)("div",{className:"flex items-start gap-2",children:[(0,We.jsx)(fe.A,{className:"w-5 h-5 text-blue-600 shrink-0 mt-0.5"}),(0,We.jsxs)("div",{className:"flex-1",children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-900",children:"Branding images"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Optional images for this share link only. Leave empty to use your organization logo everywhere."})]})]}),(0,We.jsxs)("div",{className:"rounded-lg border border-blue-200 bg-blue-50/50 p-3",children:[(0,We.jsx)("p",{className:"text-sm font-medium text-gray-800 mb-1",children:"One logo for all areas"}),(0,We.jsx)("p",{className:"text-xs text-gray-600 mb-2",children:"Upload once to set the header, cover page, and AI assistant to the same image. You can still adjust each area below."}),(0,We.jsxs)("div",{className:"flex flex-wrap items-center gap-3 mb-2",children:[(0,We.jsx)("div",{className:"w-16 h-16 shrink-0 rounded-md border border-blue-200 bg-white flex items-center justify-center overflow-hidden",children:(0,We.jsx)(Ge,{url:Yr.unifiedPreviewUrl,fallbackUrl:Yr.allEqual?Pn:null})}),Yr.allEqual&&(Yr.unifiedPreviewUrl?(0,We.jsx)("span",{className:"text-xs text-green-700 font-medium",children:"Same logo on all three areas"}):Pn?(0,We.jsx)("span",{className:"text-xs text-gray-600",children:"All areas use organization logo"}):null)]}),(0,We.jsx)("input",{ref:Rr,type:"file",accept:"image/*",className:"hidden",onChange:async e=>{var t,n;const r=null===(t=e.target.files)||void 0===t?void 0:t[0];if(e.target.value="",!r)return;if(!ie)return void Ie.Ay.error("Create a share link before uploading images.");const a=null===(n=Or.currentUser)||void 0===n?void 0:n.uid;if(a)try{J(!0);const e=(r.name.split(".").pop()||"png").replace(/[^a-zA-Z0-9]/g,""),t=e.length?e:"png",n=(0,Ee.KR)(G.IG,"users/".concat(a,"/shareableLinks/").concat(ie,"/branding-all-").concat(Date.now(),".").concat(t));await(0,Ee.D)(n,r);const i=await(0,Ee.qk)(n),s=(0,o.A)((0,o.A)({},Sn),{},{headerImageUrl:i,coverImageUrl:i,chatbotImageUrl:i});En(s),await Mr({shareBranding:s}),Ie.Ay.success("Logo applied to header, cover page, and AI assistant")}catch(i){console.error(i),Ie.Ay.error("Could not upload image")}finally{J(!1)}else Ie.Ay.error("You must be signed in to upload images.")}}),(0,We.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,We.jsx)("button",{type:"button",disabled:V||!ie,onClick:()=>{var e;return null===(e=Rr.current)||void 0===e?void 0:e.click()},className:"text-sm px-3 py-1.5 rounded-md border border-blue-300 bg-white text-blue-800 hover:bg-blue-50 disabled:opacity-50",children:"Upload logo for all"}),(0,We.jsx)("button",{type:"button",disabled:V||!_||!((Sn.headerImageUrl||"").trim()||(Sn.coverImageUrl||"").trim()||(Sn.chatbotImageUrl||"").trim()),onClick:async()=>{const e=(0,o.A)((0,o.A)({},Sn),{},{headerImageUrl:"",coverImageUrl:"",chatbotImageUrl:""});if(En(e),_&&!V)try{await Mr({shareBranding:e})}catch(t){console.error(t)}},className:"text-sm px-3 py-1.5 rounded-md border border-gray-300 bg-white text-gray-800 hover:bg-gray-50 disabled:opacity-50",children:"Use organization logo for all"})]})]}),[{fieldKey:"headerImageUrl",title:"Header",hint:"Top bar and browser tab icon on the shared page",fileRef:Dr},{fieldKey:"coverImageUrl",title:"Cover page",hint:"Large logo on the report-style cover page",fileRef:Pr},{fieldKey:"chatbotImageUrl",title:"AI assistant",hint:"Logo shown in the floating chat widget",fileRef:Tr}].map(e=>{let t=e.fieldKey,n=e.title,r=e.hint,a=e.fileRef;return(0,We.jsx)("div",{className:"rounded-lg border border-gray-200 p-3 bg-gray-50/80",children:(0,We.jsxs)("div",{className:"flex flex-wrap items-start gap-3",children:[(0,We.jsx)("div",{className:"w-16 h-16 shrink-0 rounded-md border border-gray-200 bg-white flex items-center justify-center overflow-hidden",children:(0,We.jsx)(Ge,{url:Sn[t],fallbackUrl:Pn})}),(0,We.jsxs)("div",{className:"flex-1 min-w-0 space-y-2",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-800",children:n}),(0,We.jsx)("p",{className:"text-xs text-gray-500",children:r})]}),(0,We.jsx)("input",{type:"url",value:Sn[t],onChange:e=>En(n=>(0,o.A)((0,o.A)({},n),{},{[t]:e.target.value})),onBlur:e=>{const n=e.target.value;En(e=>{const r=(0,o.A)((0,o.A)({},e),{},{[t]:n});return _&&!V&&queueMicrotask(()=>Mr({shareBranding:r})),r})},placeholder:"https://\u2026",disabled:V,className:"w-full px-2 py-1.5 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"}),(0,We.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,We.jsx)("input",{ref:a,type:"file",accept:"image/*",className:"hidden",onChange:e=>(async(e,t)=>{var n,r;const a=null===(n=t.target.files)||void 0===n?void 0:n[0];if(t.target.value="",!a)return;if(!ie)return void Ie.Ay.error("Create a share link before uploading images.");const i=null===(r=Or.currentUser)||void 0===r?void 0:r.uid;if(i)try{J(!0);const t=(a.name.split(".").pop()||"png").replace(/[^a-zA-Z0-9]/g,""),n=t.length?t:"png",r=(0,Ee.KR)(G.IG,"users/".concat(i,"/shareableLinks/").concat(ie,"/branding-").concat(e,"-").concat(Date.now(),".").concat(n));await(0,Ee.D)(r,a);const s=await(0,Ee.qk)(r),l=(0,o.A)((0,o.A)({},Sn),{},{[e]:s});En(l),await Mr({shareBranding:l}),Ie.Ay.success("Image saved")}catch(s){console.error(s),Ie.Ay.error("Could not upload image")}finally{J(!1)}else Ie.Ay.error("You must be signed in to upload images.")})(t,e)}),(0,We.jsx)("button",{type:"button",disabled:V||!ie,onClick:()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.click()},className:"text-xs px-2 py-1 rounded border border-gray-300 bg-white hover:bg-gray-50 disabled:opacity-50",children:"Upload"}),(0,We.jsx)("button",{type:"button",disabled:V||!(Sn[t]||"").trim(),onClick:()=>(async e=>{const t=(0,o.A)((0,o.A)({},Sn),{},{[e]:""});if(En(t),_&&!V)try{await Mr({shareBranding:t})}catch(n){console.error(n)}})(t),className:"text-xs px-2 py-1 rounded border border-gray-200 text-gray-600 hover:bg-gray-100 disabled:opacity-50",children:"Use org default"})]})]})]})},t)})]}),(0,We.jsxs)("div",{className:"mb-6 space-y-2",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700",children:"Theme color"}),(0,We.jsx)("p",{className:"text-xs text-gray-500",children:"Applies to buttons, links, focus rings, and other accents in both Document view and Search view, and to the cover-page CTA when enabled."}),(0,We.jsx)("div",{className:"flex flex-wrap gap-2",children:Je.map(e=>{let t=e.name,n=e.hex;return(0,We.jsx)("button",{type:"button",title:t,"aria-label":"".concat(t," (").concat(n,")"),disabled:V,onClick:()=>{fn(n),_&&!V&&Mr({reportCoverButtonColor:n})},className:"w-8 h-8 rounded-full border-2 shadow-sm shrink-0 transition-transform hover:scale-105 ".concat((0,De.qw)(hn)===n?"border-gray-900 ring-2 ring-offset-1 ring-blue-500":"border-gray-300"),style:{backgroundColor:n}},n)})}),(0,We.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,We.jsx)("input",{type:"color",value:(0,De.qw)(hn),onChange:e=>{const t=e.target.value;fn(t),_&&!V&&Mr({reportCoverButtonColor:t})},disabled:V,className:"h-10 w-16 border border-gray-300 rounded-md cursor-pointer"}),(0,We.jsx)("input",{type:"text",value:hn,onChange:e=>{const t=e.target.value;t.match(/^#[0-9A-Fa-f]{0,6}$/)&&fn(t)},onBlur:()=>{const e=(0,De.qw)(hn);fn(e),_&&!V&&Mr({reportCoverButtonColor:e})},placeholder:"#2563eb",disabled:V,className:"w-28 px-3 py-2 border border-gray-300 rounded-md font-mono text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsxs)("div",{className:"flex items-start justify-between gap-4 mb-3",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(0,We.jsx)(Ne.A,{className:"w-5 h-5 text-blue-600 shrink-0"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Cover page"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Show a cover page before viewers browse documents"})]})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer shrink-0",children:[(0,We.jsx)("input",{type:"checkbox",checked:nn,onChange:async e=>{const t=e.target.checked;rn(t);const n=(un||"").trim();if((0,W.gg)("\ud83d\udd0d Cover page toggled:",{checked:t,introLen:n.length,linkId:ie,hasLink:!!_}),!V)try{await Mr({shareAsReport:t,reportIntroduction:n}),(0,W.gg)("\ud83d\udd0d Cover page persisted to backend")}catch(r){console.error("Error updating cover page:",r)}},disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),nn&&(0,We.jsxs)("div",{className:"ml-7 mt-3",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Cover page text"}),(0,We.jsx)("textarea",{value:un,onChange:e=>mn(e.target.value),onBlur:()=>{_&&!V&&Mr()},placeholder:"Text shown on the cover page",rows:4,disabled:V,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-y"})]})]}),(0,We.jsxs)("div",{className:"border-t border-gray-200 pt-6",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-3",children:"Available Views"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mb-3",children:"Choose which views visitors can access"}),(0,We.jsxs)("div",{className:"space-y-2",children:[(0,We.jsxs)("label",{className:"flex items-center p-3 border-2 rounded-lg cursor-pointer transition-all hover:bg-gray-50 ".concat("traditional"===Kt?"border-blue-500 bg-blue-50":"border-gray-200"),children:[(0,We.jsx)("input",{type:"radio",name:"enabledViews",value:"traditional",checked:"traditional"===Kt,onChange:e=>Hr(e.target.value),disabled:V,className:"mr-3 text-blue-600 focus:ring-blue-500"}),(0,We.jsxs)("div",{className:"flex-1",children:[(0,We.jsx)("div",{className:"font-medium text-sm text-gray-900",children:"Document View Only"}),(0,We.jsx)("div",{className:"text-xs text-gray-500",children:"Document view with table of contents"})]})]}),(0,We.jsxs)("label",{className:"flex items-center p-3 border-2 rounded-lg cursor-pointer transition-all hover:bg-gray-50 ".concat("search"===Kt?"border-blue-500 bg-blue-50":"border-gray-200"),children:[(0,We.jsx)("input",{type:"radio",name:"enabledViews",value:"search",checked:"search"===Kt,onChange:e=>Hr(e.target.value),disabled:V,className:"mr-3 text-blue-600 focus:ring-blue-500"}),(0,We.jsxs)("div",{className:"flex-1",children:[(0,We.jsx)("div",{className:"font-medium text-sm text-gray-900",children:"Search View Only"}),(0,We.jsx)("div",{className:"text-xs text-gray-500",children:"Search interface with FAQs"})]})]}),(0,We.jsxs)("label",{className:"flex items-center p-3 border-2 rounded-lg cursor-pointer transition-all hover:bg-gray-50 ".concat("both"===Kt?"border-blue-500 bg-blue-50":"border-gray-200"),children:[(0,We.jsx)("input",{type:"radio",name:"enabledViews",value:"both",checked:"both"===Kt,onChange:e=>Hr(e.target.value),disabled:V,className:"mr-3 text-blue-600 focus:ring-blue-500"}),(0,We.jsxs)("div",{className:"flex-1",children:[(0,We.jsx)("div",{className:"font-medium text-sm text-gray-900",children:"Both Views"}),(0,We.jsx)("div",{className:"text-xs text-gray-500",children:"Document view with table of contents and search/FAQ view"})]})]})]})]}),O&&(0,We.jsxs)("div",{className:"border-t border-gray-200 pt-6",children:[(0,We.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Mascot mode"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Share a talking mascot link instead of the standard shared page"})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer shrink-0",children:[(0,We.jsx)("input",{type:"checkbox",checked:$t,onChange:e=>(async e=>{if(!O)return;const t=$t,n=ht;if(Xt(e),e&&ft(!0),ie&&U(_r(ie,{mascotMode:e})),_&&!V)try{await Mr((0,o.A)({mascotMode:e},e?{emailOnOpen:!0}:{}))}catch(Le){console.error("Error updating mascot mode:",Le),Xt(t),ft(n),ie&&U(_r(ie,{mascotMode:t})),Ie.Ay.error((null===Le||void 0===Le?void 0:Le.message)||"Failed to update mascot mode")}})(e.target.checked),disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-amber-200 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-amber-500"})]})]}),$t&&_&&(0,We.jsxs)("p",{className:"mt-3 text-xs text-amber-800 bg-amber-50 border border-amber-100 rounded-md px-3 py-2",children:["Visitors open your mascot at ",(0,We.jsx)("span",{className:"font-mono break-all",children:_})]})]})]}),"assistant"===sn&&(0,We.jsx)(We.Fragment,{children:(0,We.jsxs)("div",{children:[!st&&(0,We.jsxs)("p",{className:"text-sm text-gray-600 mb-4",children:["Turn this on to add a chat widget for people who open your shared link. The assistant answers from the documents you have shared","document"===zt?" in this document":" in this workspace"," \u2014 so visitors can ask questions and find information without reading everything themselves. You can customize its name, greeting, and the text in the message box below."]}),(0,We.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsx)(xe.A,{className:"w-5 h-5 text-blue-600 mr-2"}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"AI Assistant"})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer",children:[(0,We.jsx)("input",{type:"checkbox",checked:st,onChange:e=>(async e=>{if(lt(e),_)try{await Mr({isPublic:K,expiryDate:ne,includeAgent:e,agentConfig:gr,emailNotifications:ut,commentsEnabled:At})}catch(Le){console.error("Error updating agent configuration:",Le);const n=Le.message||"Failed to update agent configuration";lt(!e),n.includes("permission")||n.includes("Permission")?Ie.Ay.error("Missing or insufficient permissions. Please check your access to this workspace.",{duration:5e3}):Ie.Ay.error("Failed to update agent configuration: ".concat(n),{duration:4e3})}})(e.target.checked),disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),st&&(0,We.jsxs)("div",{className:"ml-7 space-y-4 p-4 bg-gray-50 rounded-lg",children:[(0,We.jsx)("p",{className:"text-sm text-gray-600 mb-4",children:"Customize how the assistant introduces itself and what visitors see in the chat."}),(0,We.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Assistant Name"}),(0,We.jsx)("input",{type:"text",value:gr.name,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{name:e.target.value})),onBlur:Gr,placeholder:Ur.name,className:"w-full px-3 py-2 border border
1-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Theme"}),(0,We.jsx)("select",{value:gr.theme,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{theme:e.target.value})),disabled:V,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[{id:"default",name:"Default",primary:"#3B82F6"},{id:"dark",name:"Dark",primary:"#1F2937"},{id:"green",name:"Green",primary:"#10B981"},{id:"purple",name:"Purple",primary:"#8B5CF6"},{id:"orange",name:"Orange",primary:"#F59E0B"}].map(e=>(0,We.jsx)("option",{value:e.id,children:e.name},e.id))})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Position"}),(0,We.jsx)("select",{value:gr.position,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{position:e.target.value})),disabled:V,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[{id:"bottom-right",name:"Bottom Right"},{id:"bottom-left",name:"Bottom Left"},{id:"top-right",name:"Top Right"},{id:"top-left",name:"Top Left"}].map(e=>(0,We.jsx)("option",{value:e.id,children:e.name},e.id))})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Size"}),(0,We.jsx)("select",{value:gr.size,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{size:e.target.value})),disabled:V,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[{id:"small",name:"Small"},{id:"medium",name:"Medium"},{id:"large",name:"Large"}].map(e=>(0,We.jsx)("option",{value:e.id,children:e.name},e.id))})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Welcome Message"}),(0,We.jsx)("textarea",{value:gr.welcomeMessage,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{welcomeMessage:e.target.value})),onBlur:Gr,rows:2,placeholder:Ur.welcomeMessage,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Input Placeholder"}),(0,We.jsx)("input",{type:"text",value:gr.placeholder,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{placeholder:e.target.value})),onBlur:Gr,placeholder:Ur.placeholder,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"})]}),(0,We.jsx)("div",{children:(0,We.jsxs)("label",{className:"flex items-center",children:[(0,We.jsx)("input",{type:"checkbox",checked:gr.branding,onChange:e=>qr((0,o.A)((0,o.A)({},gr),{},{branding:e.target.checked})),disabled:V,className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500"}),(0,We.jsx)("span",{className:"ml-2 text-sm text-gray-700",children:'Show "Powered by Based" branding'})]})})]}),(0,We.jsx)("div",{className:"mt-4 pt-4 border-t border-gray-200",children:(0,We.jsxs)("label",{className:"flex items-start gap-3",children:[(0,We.jsx)("input",{type:"checkbox",checked:!!gr.visitorPdfAccessForChat,onChange:async e=>{const t=(0,o.A)((0,o.A)({},gr),{},{visitorPdfAccessForChat:e.target.checked});if(qr(t),_&&!V)try{await Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:t,emailNotifications:ut,commentsEnabled:At})}catch(n){console.error("Error toggling Include PDFs:",n),Ie.Ay.error("Could not save PDF setting. Please try again.")}},disabled:V,className:"mt-0.5 rounded border-gray-300 text-blue-600 focus:ring-blue-500 shrink-0"}),(0,We.jsxs)("span",{children:[(0,We.jsx)("span",{className:"block text-sm font-medium text-gray-900",children:"Include PDFs"}),(0,We.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5",children:"When enabled, PDFs included on this share appear inline in the page, in a Files list in the sidebar, open in the PDF viewer, and can be referenced by the assistant."})]})]})}),st&&(0,We.jsxs)("div",{className:"mt-4 pt-4 border-t border-gray-200 space-y-3",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,We.jsxs)("div",{className:"flex items-center min-w-0",children:[(0,We.jsx)(xe.A,{className:"w-5 h-5 text-blue-600 mr-2 flex-shrink-0"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Live chat handoff"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Let visitors speak to your team if assistant can't help or when they explicitly ask to speak with someone live"})]})]}),ar?(0,We.jsx)("span",{className:"text-xs text-gray-500 flex-shrink-0",children:"Loading\u2026"}):(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer flex-shrink-0",children:[(0,We.jsx)("input",{type:"checkbox",checked:!!Zn&&!!tr.liveRequestsShareLinkEnabled,onChange:e=>{Zn?Wr({liveRequestsShareLinkEnabled:e.target.checked}):e.target.checked&&Vr()},disabled:V||dr,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]}),!ar&&Zn&&(0,We.jsx)(We.Fragment,{children:(0,We.jsx)(Re.K,{showTitle:!1,surfaceScope:"shareO
1nly",hideShareSurfaceToggle:!0,introText:"",workspaceId:t||null,value:tr,onChange:Wr,disabled:V,onUploadTeamMemberPhoto:Jr})})]}),(0,We.jsxs)("div",{className:"flex items-center justify-between mt-2",children:[(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsx)(Ce.A,{className:"w-5 h-5 text-blue-600 mr-2"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Email Notifications"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Get notified when visitors chat with your AI Assistant"})]})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer",children:[(0,We.jsx)("input",{type:"checkbox",checked:ut,onChange:e=>{mt(e.target.checked),_&&Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:e.target.checked,commentsEnabled:At})},disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]})]})}),"analytics"===sn&&(0,We.jsx)(We.Fragment,{children:(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsx)(Ce.A,{className:"w-5 h-5 text-blue-600 mr-2"}),(0,We.jsxs)("div",{children:[(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:$t?"Email on Mascot Open":"Email on Document Open"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:$t?"Get notified by email each time someone opens your mascot link":"Get notified by email each time someone opens your shared link"})]})]}),(0,We.jsxs)("label",{className:"relative inline-flex items-center cursor-pointer",children:[(0,We.jsx)("input",{type:"checkbox",checked:ht,onChange:async e=>{const t=e.target.checked;if(ft(t),_)try{await Mr({emailOnOpen:t}),ot.current&&(ot.current=(0,o.A)((0,o.A)({},ot.current),{},{emailOnOpen:t})),setTimeout(()=>{$r()},0)}catch(n){}},disabled:V,className:"sr-only peer"}),(0,We.jsx)("div",{className:"w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-blue-600"})]})]})})]})]})})}),(0,We.jsxs)("div",{className:"px-4 py-3 bg-gray-50 sm:px-6 flex flex-row items-center justify-between",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(St||!_)&&(0,We.jsx)("button",{type:"button",onClick:u,className:"inline-flex justify-center px-4 py-2 text-base font-medium text-gray-700 bg-white border border-gray-300 rounded-md shadow-sm hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:text-sm",children:St?"Cancel":"Close"}),h&&ie&&(0,We.jsxs)("button",{type:"button",onClick:()=>{h(),u()},className:"inline-flex items-center gap-1.5 px-4 py-2 text-sm font-medium text-red-600 bg-white border border-red-200 rounded-md shadow-sm hover:bg-red-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500",children:[(0,We.jsx)(p.A,{className:"w-4 h-4"}),"Delete"]})]}),(0,We.jsx)("button",{type:"button",onClick:()=>{St||!_?(async()=>{try{_t(!0),(0,W.gg)("\ud83d\udd35 Modal handleSave starting..."),_?await Mr({isPublic:K,expiryDate:ne,includeAgent:st,agentConfig:gr,emailNotifications:ut,emailOnOpen:ht,requireContactBeforeView:xt,commentsEnabled:At,shareAsReport:nn,reportIntroduction:un||"",reportCoverButtonColor:hn,sharedDocumentIds:An,linkLabel:xn,shareBranding:Sn}):((0,W.gg)("\ud83d\udd35 No link, generating..."),await Kr(),(0,W.gg)("\ud83d\udd35 Link generated:",_)),(0,W.gg)("\ud83d\udd35 Calling onSave with settings...");const e={isPublic:K,shareableLink:_,linkId:ie,linkExpiryDate:ne||null,includeAgent:st,agentConfig:st?gr:null,emailNotifications:ut,emailOnOpen:ht,requireContactBeforeView:xt,commentsEnabled:At,enabledViews:Kt,shareAsReport:nn,reportIntroduction:un||"",reportCoverButtonColor:(0,De.qw)(hn),shareBranding:(0,o.A)({},Sn),mascotMode:$t};await m(e),(0,W.gg)("\ud83d\udd35 onSave completed"),ot.current={isPublic:K,includeAgent:st,emailNotifications:ut,emailOnOpen:ht,requireContactBeforeView:xt,commentsEnabled:At,enabledViews:Kt,expiryDate:ne,linkId:ie,agentConfig:st?gr:null,shareAsReport:nn,reportIntroduction:un,reportCoverButtonColor:(0,De.qw)(hn),sharedDocumentIds:An,linkLabel:xn||"",shareBranding:(0,o.A)({},Sn),mascotMode:$t},Et(!1),Rt.current&&clearTimeout(Rt.current),Tt(!0),Rt.current=setTimeout(()=>{Tt(!1),Rt.current=null},2800)}catch(Le){console.error("\u274c Modal handleSave error:",Le)}finally{_t(!1)}})():u()},disabled:V||Lt,className:"inline-flex justify-center px-4 py-2 text-base font-medium border rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 sm:text-sm ".concat(V||Lt?"text-white bg-blue-400 border-transparent cursor-not-allowed":!St&&_?"bg-white text-gray-800 border border-gray-300 shadow-sm hover:bg-gray-50 focus:ring-gray-500":"text-white bg-blue-600 border-transparent hover:bg-blue-700 focus:ring-blue-500"),children:Xr})]})]})]})})):((0,W.gg)("\ud83d\udfe2 Modal render stopped because isOpen is false"),null)};var Ze=n(27019),$e=n(88693),Xe=n(7365),et=n(27673),tt=n(35087);const nt=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function rt(e){var t;const n=e&&"object"===typeof e?e:null;if(!n||!n.colors||null===(t=n.typography)||void 0===t||!t.body||!n.rounded)throw new Error("Invalid workspace theme shape");const r=n.colors;for(const o of["primary","primaryHover","surface","onSurface","hairline","focusRing"])if("string"!==typeof r[o]||!nt.test(r[o].trim()))throw new Error("Invalid theme color: ".concat(o));if("string"!==typeof n.typography.body.fontFamily||"string"!==typeof n.typography.body.fontSize)throw new Error("Invalid theme typography.body");if("string"!==typeof n.rounded.md)throw new Error("Invalid theme rounded.md")}function ot(e){rt(e);const t=function(e){rt(e);const t=e.colors,n=e.typography,r=e.rounded;return["--brand: ".concat(t.primary),"--brand-hover: ".concat(t.primaryHover),"--surface: ".concat(t.surface),"--on-surface: ".concat(t.onSurface),"--hairline: ".concat(t.hairline),"--focus-ring: ".concat(t.focusRing),"
1--font-body-family: ".concat(n.body.fontFamily),"--font-body-size: ".concat(n.body.fontSize),"--rounded-brand-md: ".concat(r.md)].join("; ")}(e),n=e.colors.surface;return'<style id="based-embed-theme">\n'+"  .based-embed-root {\n    ".concat(t,";\n  }\n")+"  .based-embed-root .faq-widget-full,\n  .based-embed-root.faq-widget-full {\n    font-family: var(--font-body-family) !important;\n    font-size: var(--font-body-size) !important;\n"+"    background: linear-gradient(to bottom right, ".concat(n,", #ffffff, #faf5ff) !important;\n")+'    color: var(--on-surface) !important;\n  }\n  .based-embed-root .faq-widget-compact {\n    font-family: var(--font-body-family) !important;\n    font-size: var(--font-body-size) !important;\n    color: var(--on-surface) !important;\n  }\n  .based-embed-root .faq-widget-full header,\n  .based-embed-root .faq-widget-compact [style*="border"] {\n    border-color: var(--hairline) !important;\n  }\n  .based-embed-root button[style*="background: rgb(37, 99, 235)"],\n  .based-embed-root button[style*="#2563eb"],\n  .based-embed-root button[style*="background: #2563eb"] {\n    background: var(--brand) !important;\n    background-color: var(--brand) !important;\n    border-color: var(--brand) !important;\n    color: #ffffff !important;\n  }\n  .based-embed-root [style*="#3b82f6"],\n  .based-embed-root [style*="#2563eb"] {\n    color: var(--brand) !important;\n    border-color: var(--brand) !important;\n  }\n  .based-embed-root svg[style*="#3b82f6"],\n  .based-embed-root svg {\n    color: var(--brand) !important;\n  }\n</style>'}function at(e){const t=(0,Le.x5)({workspaceTheme:e}).typography.body.fontFamily;return/Inter/i.test(t)?"inter":/Roboto/i.test(t)&&!/Roboto Mono/i.test(t)?"roboto":/Open Sans/i.test(t)?"open-sans":/Lato/i.test(t)?"lato":/Montserrat/i.test(t)?"montserrat":/Poppins/i.test(t)?"poppins":"system"}function it(e){const t=e.typography.body.fontSize.trim();return"0.875rem"===t?"small":"1rem"===t?"medium":"1.125rem"===t?"large":"1.25rem"===t?"xlarge":"medium"}function st(e){rt(e);const t=e.colors;return{"--brand":t.primary,"--brand-hover":t.primaryHover,"--surface":t.surface,"--on-surface":t.onSurface,"--hairline":t.hairline,"--focus-ring":t.focusRing,"--font-body-family":e.typography.body.fontFamily,"--font-body-size":e.typography.body.fontSize,"--rounded-brand-md":e.rounded.md}}var lt=n(75088),dt=n(44919),ct=n(56099),ut=n(99482),mt=n(11720),pt=n(74634),gt=n(6858),ht=n(91462),ft=n(45580),yt=n(97885),vt=n(36401),xt=n(38288);const bt=e=>{var t,n;let r=e.workspaceId,s=e.linkId,l=e.organizationName,d=void 0===l?"Knowledge Base":l,u=e.organizationLogo,m=void 0===u?null:u,p=e.containerId,g=void 0===p?"faq-widget-container":p,h=(e.theme,e.displayMode),f=void 0===h?"full":h,y=e.workspaceTheme,v=void 0===y?ht.i:y,x=e.onFAQClick,b=void 0===x?null:x,w=e.isInternalSetup,k=void 0!==w&&w,A=e.viewerBaseOrigin,j=void 0===A?null:A;const N=(0,i.useState)([]),C=(0,a.A)(N,2),S=C[0],E=C[1],I=(0,i.useState)(""),D=(0,a.A)(I,2),P=D[0],T=D[1],O=(0,i.useState)(!1),F=(0,a.A)(O,2),L=F[0],U=F[1],M=(0,i.useState)(null),z=(0,a.A)(M,2),B=z[0],W=z[1],V=(0,i.useState)(!0),J=(0,a.A)(V,2),q=J[0],H=J[1],G=(0,i.useState)(null),K=(0,a.A)(G,2),Q=K[0],Y=K[1],Z=(0,i.useState)(null),$=(0,a.A)(Z,2),X=$[0],ee=$[1],te=(0,i.useState)(null),ne=(0,a.A)(te,2),re=(ne[0],ne[1]),oe=(0,i.useState)([]),ae=(0,a.A)(oe,2),ie=ae[0],se=ae[1],le=(0,i.useRef)([]),de=(0,i.useRef)(null),ce=(0,i.useRef)(null),ue=(0,i.useRef)(""),me=(0,i.useRef)(null),pe=(0,i.useMemo)(()=>{const e=st(v);return"full"===f?(0,o.A)((0,o.A)({},e),{},{minHeight:"100vh",background:"linear-gradient(to bottom right, ".concat(v.colors.surface,", #ffffff, #faf5ff)")}):(0,o.A)((0,o.A)({},e),{},{color:v.colors.onSurface})},[v,f]),ge={FileText:R.A,Clock:lt.A,TrendingUp:dt.A};(0,i.useEffect)(()=>{(r||s)&&(async()=>{H(!0),Y(null);try{const e=new URLSearchParams;r&&e.append("workspaceId",r),s&&e.append("linkId",s);const t=await fetch("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/getFAQData?".concat(e.toString()),{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error("HTTP ".concat(t.status,": ").concat(t.statusText));const n=await t.json(),a=(n.faqs||[]).map(e=>{const t=e.iconName||"FileText";return(0,o.A)((0,o.A)({},e),{},{icon:ge[t]||R.A})});E(a),re(n.schema),ee(n.organization||{name:d,logoUrl:m}),n.schema&&(0,mt.dB)(n.schema,"faq-widget-schema")}catch(e){console.error("Error fetching FAQ data:",e),Y(e.message)}finally{H(!1)}})()},[r,s]),(0,i.useEffect)(()=>
1{if(!r)return;let e=!1;return fetch("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/getWidgetDocuments?workspaceId=".concat(encodeURIComponent(r))).then(e=>e.json()).then(t=>{e||se(Array.isArray(null===t||void 0===t?void 0:t.documents)?t.documents:[])}).catch(()=>{e||se([])}),()=>{e=!0}},[r]),(0,i.useEffect)(()=>()=>{var e;null===(e=de.current)||void 0===e||e.abort(),de.current=null,null!=ce.current&&(cancelAnimationFrame(ce.current),ce.current=null)},[]);const he=async e=>{var t;if(!e.trim()||L||!r)return;null===(t=de.current)||void 0===t||t.abort(),null!=ce.current&&(cancelAnimationFrame(ce.current),ce.current=null);const n=new AbortController;de.current=n,U(!0),W(null);try{const t="search_".concat(r,"_").concat(Date.now()),a=le.current.slice(-10),i=(0,vt.Ww)({workspaceId:r,chatId:t,message:e,surface:xt.qN.FAQ_WIDGET,ragAudience:"visitor",conversationHistory:a,documents:ie,extras:(0,o.A)({},k?{skipChatLogPersistence:!0}:{})});let s="";if(k){const t=await fetch((0,pt.CN)(),{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)});if(!t.ok)throw new Error("HTTP ".concat(t.status));const n=await t.json(),r=n.result||n.data||n;s=r.content?r.content:r.message?r.message:r.response?r.response:r.answer?r.answer:"string"===typeof r?r:"I couldn't find an answer to your question. Please try rephrasing or contact support.";const o=r.ragContext&&Array.isArray(r.ragContext.pdfSources)?r.ragContext.pdfSources:[],l=r.ragContext&&Array.isArray(r.ragContext.viewerDocuments)?r.ragContext.viewerDocuments:[];W({query:e,answer:s,pdfSources:o,viewerDocuments:l,timestamp:Date.now()}),le.current=[...a,{role:"user",content:e},{role:"assistant",content:s}].slice(-10)}else{let t="",r=!1;ue.current="",W({query:e,answer:"",streaming:!0,timestamp:Date.now()});const o=await(0,gt.R)(i,{onDelta:n=>{r||(r=!0,U(!1)),t+=n,ue.current=t,null==ce.current&&(ce.current=requestAnimationFrame(()=>{ce.current=null,W({query:e,answer:ue.current,streaming:!0,timestamp:Date.now()})}))}},{signal:n.signal});null!=ce.current&&(cancelAnimationFrame(ce.current),ce.current=null),s=o.content&&String(o.content).trim()?o.content:t||"I couldn't find an answer to your question. Please try rephrasing or contact support.";const l=o.ragContext&&Array.isArray(o.ragContext.pdfSources)?o.ragContext.pdfSources:[],d=o.ragContext&&Array.isArray(o.ragContext.viewerDocuments)?o.ragContext.viewerDocuments:[];W({query:e,answer:s,pdfSources:l,viewerDocuments:d,streaming:!1,timestamp:Date.now()}),le.current=[...a,{role:"user",content:e},{role:"assistant",content:s}].slice(-10)}}catch(Q){if(Q&&"AbortError"===Q.name)return;console.error("Error searching:",Q),W({query:e,answer:"Sorry about that \u2014 I'm having a little trouble right now. Please try again in a moment.",timestamp:Date.now(),error:!0})}finally{U(!1)}},fe=e=>{b?b(e):(T(e),he(e))},ye=()=>{var e;null===(e=de.current)||void 0===e||e.abort(),de.current=null,null!=ce.current&&(cancelAnimationFrame(ce.current),ce.current=null),T(""),W(null),le.current=[]},ve=(0,i.useMemo)(()=>{const e=(null===B||void 0===B?void 0:B.answer)||"",t=null===B||void 0===B?void 0:B.streaming,n=null===B||void 0===B?void 0:B.viewerDocuments,r=null!=j&&String(j).trim()||("undefined"!==typeof window?window.location.origin:""),o=!t&&Array.isArray(n)&&n.length>0?{viewerDocuments:n,shareLinkId:s||null,viewerBaseOrigin:r||null}:{};return(0,yt.c)(e,o)},[null===B||void 0===B?void 0:B.answer,null===B||void 0===B?void 0:B.streaming,null===B||void 0===B?void 0:B.viewerDocuments,s,j]),xe=(null===B||void 0===B?void 0:B.streaming)&&!String((null===B||void 0===B?void 0:B.answer)||"").trim();(0,i.useEffect)(()=>{if(null===B||void 0===B||!B.streaming)return;const e=document.getElementById("search-results");xe?null===e||void 0===e||e.scrollIntoView({block:"nearest",behavior:"smooth"}):requestAnimationFrame(()=>{var e;null===(e=me.current)||void 0===e||e.scrollIntoView({block:"end",behavior:"auto"})})},[null===B||void 0===B?void 0:B.streaming,null===B||void 0===B?void 0:B.answer,xe]);const be=X||{name:d,logoUrl:m};return q?(0,We.jsxs)("div",{className:"faq-widget-loading based-embed-root",style:(0,o.A)({padding:"2rem",textAlign:"center"},st(v)),children:[(0,We.jsx)(Se.y$,{size:"md",className:"mx-auto"}),(0,We.jsx)("p",{style:{marginTop:"1rem",color:"#6b7280"},children:"Loading FAQs..."})]}):Q?(0,We.jsx)("div",{className:"faq-widget-error",style:{padding:"2rem",textAlign:"center",color:"#dc2626"},children:(0,We.jsxs)("p",{children:["Error loading FAQs: ",Q]})}):"compact"===f?(0,We.jsx)("div",{className:"based-embed-root faq-widget-compact",id:g,style:pe,children:S.length>0&&(0,We.jsxs)("div",{children:[(0,We.jsx)("h3",{style:{fontSize:"1.25rem",fontWeight:"bold",marginBottom:"1rem"},children:"Frequently Asked Questions"}),(0,We.jsx)("div",{style:{display:"grid",gap:"0.75rem"},children:S.slice(0,5).map(e=>{const t=e.icon;return(0,We.jsxs)("button",{onClick:()=>
1fe(e.question),style:{display:"flex",alignItems:"start",gap:"0.75rem",padding:"0.75rem",background:"white",border:"1px solid var(--hairline)",borderRadius:"0.5rem",textAlign:"left",cursor:"pointer",transition:"all 0.2s"},onMouseEnter:e=>{e.currentTarget.style.borderColor="var(--brand)",e.currentTarget.style.boxShadow="0 1px 3px rgba(0,0,0,0.1)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="var(--hairline)",e.currentTarget.style.boxShadow="none"},children:[(0,We.jsx)(t,{style:{width:"1.25rem",height:"1.25rem",color:"var(--brand)",flexShrink:0,marginTop:"0.125rem"}}),(0,We.jsx)("span",{style:{fontSize:"0.875rem",fontWeight:"500",color:"#111827"},children:e.question})]},e.id||e.question)})})]})}):(0,We.jsxs)("div",{className:"based-embed-root faq-widget-full",id:g,style:pe,children:[(0,We.jsx)("header",{style:{background:"rgba(255, 255, 255, 0.8)",backdropFilter:"blur(4px)",borderBottom:"1px solid var(--hairline)",position:"sticky",top:0,zIndex:40},children:(0,We.jsx)("div",{style:{width:"100%",padding:"1rem 1.5rem"},children:(0,We.jsx)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:(0,We.jsx)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:be.logoUrl?(0,We.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[(0,We.jsx)("img",{src:be.logoUrl,alt:be.name,style:{height:"2.5rem",maxWidth:"200px",objectFit:"contain"},crossOrigin:"anonymous"}),(0,We.jsx)("span",{style:{fontSize:"1.125rem",fontWeight:"600",color:"#111827"},children:be.name})]}):(0,We.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"0.75rem"},children:[(0,We.jsx)("div",{style:{height:"2.5rem",width:"2.5rem",background:"var(--brand)",color:"white",borderRadius:"0.5rem",display:"flex",alignItems:"center",justifyContent:"center"},children:(0,We.jsx)("span",{style:{fontSize:"1.25rem",fontWeight:"bold"},children:be.name.charAt(0).toUpperCase()})}),(0,We.jsx)("span",{style:{fontSize:"1.125rem",fontWeight:"600",color:"#111827"},children:be.name})]})})})})}),(0,We.jsxs)("div",{style:{maxWidth:"64rem",margin:"0 auto",padding:"4rem 1.5rem 3rem"},children:[(0,We.jsxs)("div",{style:{textAlign:"center",marginBottom:"3rem"},children:[(0,We.jsx)("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"center",width:"4rem",height:"4rem",background:"color-mix(in srgb, var(--brand) 18%, white)",borderRadius:"50%",marginBottom:"1rem"},children:(0,We.jsx)(ct.A,{style:{width:"2rem",height:"2rem",color:"var(--brand)"}})}),(0,We.jsx)("h1",{style:{fontSize:"2.25rem",fontWeight:"bold",color:"#111827",marginBottom:"1rem"},children:"How can we help you today?"}),(0,We.jsx)("p",{style:{fontSize:"1.25rem",color:"#4b5563",maxWidth:"32rem",margin:"0 auto"},children:"Search our knowledge base or browse frequently asked questions"})]}),(0,We.jsx)("form",{onSubmit:e=>{e.preventDefault(),he(P)},style:{marginBottom:"2rem"},children:(0,We.jsxs)("div",{style:{position:"relative"},children:[(0,We.jsx)("div",{style:{position:"absolute",top:0,bottom:0,left:0,paddingLeft:"1rem",display:"flex",alignItems:"center",pointerEvents:"none"},children:(0,We.jsx)(_.A,{style:{width:"1.5rem",height:"1.5rem",color:"#9ca3af"}})}),(0,We.jsx)("input",{type:"text",value:P,onChange:e=>T(e.target.value),placeholder:"Ask a question or search for topics...",style:{width:"100%",paddingLeft:"3rem",paddingRight:"8rem",paddingTop:"1.25rem",paddingBottom:"1.25rem",fontSize:"1.125rem",border:"2px solid var(--hairline)",borderRadius:"1rem",outline:"none",boxShadow:"0 10px 15px -3px rgba(0,0,0,0.1)",transition:"all 0.2s"},onFocus:e=>{e.currentTarget.style.borderColor="var(--brand)",e.currentTarget.style.boxShadow="0 0 0 3px color-mix(in srgb, var(--brand) 25%, transparent)"},onBlur:e=>{e.currentTarget.style.borderColor="var(--hairline)",e.currentTarget.style.boxShadow="0 10px 15px -3px rgba(0,0,0,0.1)"},disabled:L}),(0,We.jsxs)("div",{style:{position:"absolute",top:0,bottom:0,right:0,display:"flex",alignItems:"center",paddingRight:"0.75rem",gap:"0.5rem"},children:[P&&!L&&(0,We.jsx)("button",{type:"button",onClick:ye,style:{padding:"0.5rem",color:"#9ca3af",background:"transparent",border:"none",cursor:"pointer",borderRadius:"0.5rem"},children:(0,We.jsx)(c.A,{style:{width:"1.25rem",height:"1.25rem"}})}),(0,We.jsx)("button",{type:"submit",disabled:!P.trim()||L,style:{padding:"0.625rem 1.5rem",background:"var(--brand)",color:"white",border:"none",borderRadius:"0.75rem",fontWeight:"500",cursor:L||!P.trim()?"not-allowed":"pointer",opacity:L||!P.trim()?.5:1,transition:"all 0.2s"},children:L?(0,We.jsx)(Se.y$,{size:"sm"}):"Search"})]})]})}),B&&(0,We.jsx)("div",{id:"search-results",style:{marginBottom:"3rem",scrollMarginTop:"2rem"},children:(0,We.jsxs)("div",{style:{background:"white",borderRadius:"1rem",boxShadow:"0 20px 25px -5px rgba(0,0,0,0.1)",padding:"2rem",border:"2px s
1olid",borderColor:B.error?"#fecaca":"color-mix(in srgb, var(--brand) 35%, white)"},children:[(0,We.jsxs)("div",{style:{display:"flex",alignItems:"start",gap:"1rem",marginBottom:"1rem"},children:[(0,We.jsx)("div",{style:{flexShrink:0,width:"2.5rem",height:"2.5rem",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:B.error?"#fee2e2":"color-mix(in srgb, var(--brand) 18%, white)"},children:(0,We.jsx)(ct.A,{style:{width:"1.5rem",height:"1.5rem",color:B.error?"#dc2626":"var(--brand)"}})}),(0,We.jsxs)("div",{style:{flex:1},children:[(0,We.jsx)("h3",{style:{fontSize:"1.125rem",fontWeight:"600",color:"#111827",marginBottom:"1rem"},children:B.query}),xe?(0,We.jsx)(ut.C,{}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("div",{className:"prose prose-sm max-w-none text-gray-700 [&_a]:text-blue-600",style:{color:"#374151",lineHeight:"1.75"},dangerouslySetInnerHTML:{__html:ve}}),B.streaming?(0,We.jsx)("div",{ref:me,style:{height:1,width:"100%",overflow:"hidden",scrollMarginTop:"1.5rem"},"aria-hidden":!0}):null,!B.streaming&&(null!==(t=null===(n=B.pdfSources)||void 0===n?void 0:n.length)&&void 0!==t?t:0)>0&&(0,We.jsx)(ft.E,{className:"mt-3",pdfSources:B.pdfSources,shareLinkId:s||null,viewerBaseOrigin:j})]})]})]}),(0,We.jsx)("button",{onClick:ye,style:{marginTop:"1rem",fontSize:"0.875rem",color:"#6b7280",background:"transparent",border:"none",cursor:"pointer",fontWeight:"500"},children:"\u2190 New search"})]})}),!B&&S.length>0&&(0,We.jsxs)("div",{children:[(0,We.jsx)("h2",{style:{fontSize:"1.5rem",fontWeight:"bold",color:"#111827",marginBottom:"1.5rem",textAlign:"center"},children:"Frequently Asked Questions"}),(0,We.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(250px, 1fr))",gap:"1rem"},children:S.map(e=>{const t=e.icon;return(0,We.jsx)("button",{onClick:()=>fe(e.question),style:{background:"white",borderRadius:"0.75rem",padding:"1.5rem",boxShadow:"0 4px 6px -1px rgba(0,0,0,0.1)",textAlign:"left",border:"2px solid transparent",cursor:"pointer",transition:"all 0.2s",transform:"translateY(0)"},onMouseEnter:e=>{e.currentTarget.style.borderColor="color-mix(in srgb, var(--brand) 40%, white)",e.currentTarget.style.boxShadow="0 20px 25px -5px rgba(0,0,0,0.1)",e.currentTarget.style.transform="translateY(-4px)"},onMouseLeave:e=>{e.currentTarget.style.borderColor="transparent",e.currentTarget.style.boxShadow="0 4px 6px -1px rgba(0,0,0,0.1)",e.currentTarget.style.transform="translateY(0)"},children:(0,We.jsxs)("div",{style:{display:"flex",alignItems:"start",gap:"1rem"},children:[(0,We.jsx)("div",{style:{flexShrink:0,width:"2.5rem",height:"2.5rem",background:"color-mix(in srgb, var(--brand) 18%, white)",borderRadius:"0.5rem",display:"flex",alignItems:"center",justifyContent:"center"},children:(0,We.jsx)(t,{style:{width:"1.25rem",height:"1.25rem",color:"var(--brand)"}})}),(0,We.jsx)("div",{style:{flex:1},children:(0,We.jsx)("h3",{style:{fontSize:"0.875rem",fontWeight:"600",color:"#111827"},children:e.question})})]})},e.id||e.question)})})]})]})]})};function wt(e){const t=(0,De.qw)(e,"#000000");return{r:parseInt(t.slice(1,3),16)/255,g:parseInt(t.slice(3,5),16)/255,b:parseInt(t.slice(5,7),16)/255}}function kt(e){return e<=.03928?e/12.92:((e+.055)/1.055)**2.4}function At(e){return.2126*kt(e.r)+.7152*kt(e.g)+.0722*kt(e.b)}const jt="#ffffff";function Nt(e){const t=function(e,t){const n=At(wt(e)),r=At(wt(t));return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}(e.colors.primary,jt);return t<4.5?{ok:!1,message:"textColor (".concat(jt,") on backgroundColor (").concat(e.colors.primary,") has contrast ratio ").concat(t.toFixed(2),":1, below WCAG AA minimum of 4.5:1.")}:{ok:!0}}const Ct=e=>{let t=e.isOpen,n=e.onClose,r=e.workspaceId,s=e.linkId,l=(e.knowledgeBaseTitle,e.initialShareBranding),u=void 0===l?null:l;const m=(0,i.useState)(""),g=(0,a.A)(m,2),h=g[0],f=g[1],y=(0,i.useState)(!1),b=(0,a.A)(y,2),k=b[0],A=b[1],j=(0,i.useState)("#faq-widget-container"),N=(0,a.A)(j,2),C=N[0],S=N[1],E=(0,i.useState)("auto"),I=(0,a.A)(E,2),D=I[0],P=I[1],T=(0,i.useState)("full"),R=(0,a.A)(T,2),O=R[0],F=R[1],L=(0,i.useState)("script"),_=(0,a.A)(L,2),U=_[0],M=_[1],z=(0,i.useState)("100%"),V=(0,a.A)(z,2),J=V[0],q=V[1],H=(0,i.useState)("800px"),K=(0,a.A)(H,2),Q=K[0],Y=K[1],Z=(0,i.useState)(null),$=(0,a.A)(Z,2),X=$[0],ee=$[1],te=(0,i.useState)(()=>
1(0,Le.x5)(u)),ne=(0,a.A)(te,2),re=ne[0],oe=ne[1],ae=(0,i.useMemo)(()=>u?JSON.stringify(u):"",[u]),ie=(0,i.useState)(!1),se=(0,a.A)(ie,2),le=se[0],de=se[1],ce=(0,i.useState)("faqs"),ue=(0,a.A)(ce,2),me=ue[0],pe=ue[1],ge=(0,i.useState)([]),he=(0,a.A)(ge,2),fe=he[0],ye=he[1],ve=(0,i.useState)(!1),xe=(0,a.A)(ve,2),be=xe[0],we=xe[1],ke=(0,i.useState)(!1),Ae=(0,a.A)(ke,2),je=Ae[0],Ne=Ae[1],Ce=(0,i.useState)(!1),Ee=(0,a.A)(Ce,2),Pe=Ee[0],Te=Ee[1];(0,i.useEffect)(()=>{t&&oe((0,Le.x5)(u||{}))},[t,ae]);const Re=at(re),Oe=it(re),_e=(0,i.useMemo)(()=>Nt(re),[re]),Ue=_e.ok?null:_e.message,Me=(0,i.useMemo)(()=>ot(re).replace(/\.based-embed-root/g,"#embed-preview-container.based-embed-root").replace('id="based-embed-theme"','id="embed-preview-theme-styles"'),[re]);(0,i.useEffect)(()=>{const e=at(re);if(!t||"system"===e||!["inter","roboto","open-sans","lato","montserrat","poppins"].includes(e))return;const n={inter:"Inter",roboto:"Roboto","open-sans":"Open+Sans",lato:"Lato",montserrat:"Montserrat",poppins:"Poppins"}[e],r="faq-widget-font-".concat(e),o=document.getElementById(r);o&&o.remove();const a=document.createElement("link");return a.id=r,a.rel="stylesheet",a.href="https://fonts.googleapis.com/css2?family=".concat(n,":wght@400;500;600;700&display=swap"),document.head.appendChild(a),()=>{const e=document.getElementById(r);e&&e.remove()}},[t,re]);(0,i.useEffect)(()=>{t||(pe("faqs"),ye([]),ee(null))},[t]),(0,i.useEffect)(()=>{if(t)return s||r?void 0:(Ie.Ay.error("Please enable Public Link first to generate embed code.",{duration:4e3}),void setTimeout(()=>{n()},100))},[t,s,r,n]),(0,i.useEffect)(()=>{if(!t||!r)return;(async()=>{we(!0);try{const e=new URLSearchParams;r&&e.append("workspaceId",r),s&&e.append("linkId",s);const t=await fetch("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/getFAQData?".concat(e.toString()),{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error("HTTP ".concat(t.status,": ").concat(t.statusText));const n=await t.json();ye(n.faqs||[])}catch(e){console.error("Error fetching FAQs:",e),Ie.Ay.error("Failed to load FAQs. Please try again.")}finally{we(!1)}})()},[t,r,s]);(0,i.useEffect)(()=>{if(t)try{if(ee(null),"iframe"===U){if(!s)return ee("linkId is required for iframe embed. Please use the script method or enable Public Link."),void f("");const e=(e=>{const t=e.linkId,n=e.width,r=void 0===n?"100%":n,o=e.height,a=void 0===o?"800px":o,i=e.baseUrl,s=void 0===i?"https://aiknowledgebase-7427e.web.app":i,l=e.includeSEOHelper,d=void 0===l||l;if(!t)throw new Error("linkId is required for iframe embed");const c="".concat(s,"/shared/").concat(t);let u="\x3c!-- FAQ Iframe Embed --\x3e\n";return d&&(u+='<script src="'.concat(s,'/faq-iframe-seo-helper.js"><\/script>\n')),u+='<iframe src="'.concat(c,'" width="').concat(r,'" height="').concat(a,'" frameborder="0" style="border: none;"></iframe>'),u})({linkId:s,width:J,height:Q});(0,W.gg)("Generated iframe embed code:",e),f(e)}else{const e={container:C,faqColorScheme:D,displayMode:O,workspaceTheme:re},t=s&&"string"===typeof s?s.trim():s,n=r&&"string"===typeof r?r.trim():r;t?e.linkId=t:n&&(e.workspaceId=n);const o=(e=>{var t;const n=[];e.workspaceId||e.linkId||n.push("Either workspaceId or linkId is required"),e.workspaceId&&e.linkId&&n.push("Cannot specify both workspaceId and linkId");const r=null!==(t=e.faqColorScheme)&&void 0!==t?t:e.theme;r&&!["auto","light","dark"].includes(r)&&n.push("Theme must be one of: auto, light, dark"),e.displayMode&&!["full","compact"].includes(e.displayMode)&&n.push("Display mode must be one of: full, compact"),e.container&&(String(e.container).match(/^[#.]?[a-zA-Z0-9_-]+$/)||n.push("Container must be a valid CSS selector (e.g., #id, .class, or id)"));return{isValid:0===n.length,errors:n}})(e);if(!o.isValid)return ee(o.errors.join(", ")),void f("");const a=(e=>{const t=e.workspaceId,n=e.linkId,r=e.container,o=void 0===r?"#faq-widget-container":r,a=e.faqColorScheme,i=void 0===a?"auto":a,s=e.displayMode,l=void 0===s?"full":s,d=e.baseUrl,c=void 0===d?"https://aiknowledgebase-7427e.web.app":d,u=e.workspaceTheme,m=(0,Le.x5
1)(null!=u&&"object"===typeof u?{workspaceTheme:u}:{});if(!t&&!n)throw new Error("workspaceId or linkId is required");const p=o.startsWith("#")||o.startsWith(".")?o.substring(1):o,g=o.startsWith("#")||o.startsWith(".")?o:"#"+o;let h="\x3c!-- FAQ Widget Embed --\x3e\n";const f=at(m);"system"!==f&&["inter","roboto","open-sans","lato","montserrat","poppins"].includes(f)&&(h+='<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family='.concat({inter:"Inter",roboto:"Roboto","open-sans":"Open+Sans",lato:"Lato",montserrat:"Montserrat",poppins:"Poppins"}[f],':wght@400;500;600;700&display=swap">\n'));const y=ot(m).replace('id="based-embed-theme"','id="faq-widget-custom-styles"');h+="".concat(y,"\n"),h+='<div id="'.concat(p,'" class="based-embed-root"'),t&&(h+=' data-workspace-id="'.concat(t,'"')),n&&(h+=' data-link-id="'.concat(n,'"')),h+=' data-display-mode="'.concat(l,'"'),h+="></div>\n",h+='<script src="'.concat(c,'/faq-widget.js"'),t&&(h+=' data-workspace-id="'.concat(t,'"')),n&&(h+=' data-link-id="'.concat(n,'"')),h+=' data-container="'.concat(g,'"'),"auto"!==i&&(h+=' data-theme="'.concat(i,'"')),h+=' data-display-mode="'.concat(l,'"'),"https://aiknowledgebase-7427e.web.app"!==c&&(h+=' data-base-url="'.concat(c,'"'));const v=it(m);return f&&"system"!==f&&(h+=' data-font-family="'.concat(f,'"')),v&&"medium"!==v&&(h+=' data-font-size="'.concat(v,'"')),h+=' data-bg-color="'.concat(m.colors.surface,'"'),h+=' data-accent-color="'.concat(m.colors.primary,'"'),h+="><\/script>",h})(e);(0,W.gg)("Generated embed code:",a),f(a)}}catch(e){ee(e.message),f("")}},[t,r,s,C,D,O,U,J,Q,re]);return t?(0,We.jsx)("div",{className:"fixed inset-0 z-[10000] overflow-y-auto",children:(0,We.jsxs)("div",{className:"flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0",children:[(0,We.jsx)("div",{className:"fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75",onClick:n}),(0,We.jsxs)("div",{className:"inline-block overflow-hidden text-left align-bottom transition-all transform bg-white rounded-lg shadow-xl sm:my-8 sm:align-middle sm:max-w-7xl sm:w-full",children:[(0,We.jsx)("div",{className:"px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4",children:(0,We.jsx)("div",{className:"sm:flex sm:items-start",children:(0,We.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,We.jsxs)("h3",{className:"text-lg font-medium leading-6 text-gray-900 flex items-center gap-2",children:[(0,We.jsx)(v.A,{className:"w-5 h-5"}),"Get Embed Code"]}),(0,We.jsx)("button",{onClick:n,className:"text-gray-400 hover:text-gray-500",children:(0,We.jsx)(c.A,{className:"w-5 h-5"})})]}),(0,We.jsxs)("div",{className:"flex gap-2 mb-4 border-b border-gray-200",children:[(0,We.jsx)("button",{onClick:()=>pe("faqs"),className:"px-4 py-2 text-sm font-medium border-b-2 transition-colors ".concat("faqs"===me?"border-blue-600 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700"),children:"FAQ Preview"}),(0,We.jsx)("button",{onClick:()=>pe("embed"),className:"px-4 py-2 text-sm font-medium border-b-2 transition-colors ".concat("embed"===me?"border-blue-600 text-blue-600":"border-transparent text-gray-500 hover:text-gray-700"),children:"Embed Code"})]}),X&&(0,We.jsxs)("div",{className:"mt-2 p-3 bg-red-50 rounded-md",children:[(0,We.jsx)("p",{className:"text-sm text-red-700 font-medium",children:X}),X.includes("workspaceId or linkId is required")&&(0,We.jsx)("p",{className:"text-xs text-red-600 mt-2",children:"Please enable Public Link first, then return here to get your embed code."})]}),!X&&!s&&!r&&(0,We.jsxs)("div",{className:"mt-2 p-3 bg-yellow-50 rounded-md",children:[(0,We.jsx)("p",{className:"text-sm text-yellow-700 font-medium",children:"No public link available"}),(0,We.jsx)("p",{className:"text-xs text-yellow-600 mt-1",children:"Please enable Public Link first to generate embed code."})]}),"faqs"===me&&(0,We.jsxs)("div",{className:"mt-4 space-y-4",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsxs)("div",{children:[(0,We.jsxs)("h4",{className:"text-md font-medium text-gray-900",children:["Preview FAQs ",fe.length>0&&"(".concat(fe.length,")")]}),(0,We.jsx)("p",{className:"text-sm text-gray-500 mt-1",children:"Review and manage FAQs before generating embed code"})]}),(0,We.jsxs)("div",{className:"flex gap-2",children:[(0,We.jsx)("button",{onClick:async()=>
1{if(r){Ne(!0);try{const e=new URLSearchParams;e.append("workspaceId",r),s&&e.append("linkId",s),e.append("generateMore","true");const t=await fetch("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/getFAQData?".concat(e.toString()),{method:"GET",headers:{Accept:"application/json"}});if(!t.ok)throw new Error("HTTP ".concat(t.status,": ").concat(t.statusText));const n=(await t.json()).faqs||[];ye(e=>{const t=new Set(e.map(e=>e.question)),r=n.filter(e=>!t.has(e.question));return[...e,...r]});const o=n.filter(e=>!fe.some(t=>t.question===e.question)).length;Ie.Ay.success("Generated ".concat(o," new FAQs"))}catch(e){console.error("Error generating more FAQs:",e),Ie.Ay.error("Failed to generate more FAQs. Please try again.")}finally{Ne(!1)}}else Ie.Ay.error("Workspace ID is required")},disabled:je||!r,className:"inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md bg-blue-50 text-blue-700 border border-blue-200 hover:bg-blue-100 disabled:opacity-50 disabled:cursor-not-allowed",children:je?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Se.y$,{size:"sm",className:"mr-1"}),"Generating..."]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(x.A,{className:"w-4 h-4 mr-1"}),"Generate More"]})}),(0,We.jsx)("button",{onClick:async()=>{if(r&&0!==fe.length){Te(!0);try{const e=(0,B.doc)(G.db,"workspaces",r);await(0,B.mZ)(e,{savedFAQs:fe,faqsUpdatedAt:new Date}),Ie.Ay.success("FAQs saved successfully!"),pe("embed")}catch(e){console.error("Error saving FAQs:",e),Ie.Ay.error("Failed to save FAQs. Please try again.")}finally{Te(!1)}}else Ie.Ay.error("No FAQs to save")},disabled:Pe||0===fe.length,className:"inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md bg-green-50 text-green-700 border border-green-200 hover:bg-green-100 disabled:opacity-50 disabled:cursor-not-allowed",children:Pe?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Se.y$,{size:"sm",className:"mr-1"}),"Saving..."]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)($e.A,{className:"w-4 h-4 mr-1"}),"Save & Continue"]})})]})]}),be?(0,We.jsxs)("div",{className:"flex items-center justify-center py-12",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-600"}),(0,We.jsx)("span",{className:"ml-2 text-sm text-gray-600",children:"Loading FAQs..."})]}):0===fe.length?(0,We.jsx)("div",{className:"text-center py-12 bg-gray-50 rounded-md",children:(0,We.jsx)("p",{className:"text-sm text-gray-500",children:'No FAQs found. Click "Generate More" to create FAQs.'})}):(0,We.jsx)("div",{className:"space-y-3 max-h-96 overflow-y-auto",children:fe.map((e,t)=>(0,We.jsx)("div",{className:"p-4 bg-gray-50 rounded-md border border-gray-200 hover:border-gray-300 transition-colors",children:(0,We.jsxs)("div",{className:"flex items-start justify-between gap-4",children:[(0,We.jsxs)("div",{className:"flex-1",children:[(0,We.jsx)("div",{className:"flex items-center gap-2 mb-2",children:(0,We.jsx)("span",{className:"text-xs font-medium text-blue-600 bg-blue-50 px-2 py-0.5 rounded",children:e.category||"General"})}),(0,We.jsx)("h5",{className:"text-sm font-semibold text-gray-900 mb-1",children:e.question}),e.answer&&(0,We.jsx)("p",{className:"text-sm text-gray-600 line-clamp-2",children:e.answer})]}),(0,We.jsx)("button",{onClick:()=>(e=>{ye(t=>t.filter((t,n)=>n!==e)),Ie.Ay.success("FAQ removed")})(t),className:"flex-shrink-0 p-1.5 text-gray-400 hover:text-red-600 hover:bg-red-50 rounded transition-colors",title:"Remove FAQ",children:(0,We.jsx)(p.A,{className:"w-4 h-4"})})]})},t))}),(0,We.jsx)("div",{className:"p-4 bg-blue-50 rounded-md",children:(0,We.jsxs)("p",{className:"text-sm text-blue-800",children:[(0,We.jsx)("strong",{children:"Tip:"})," Review your FAQs and remove any that aren't relevant. You can generate more FAQs if needed. Once you're satisfied, click \"Save & Continue\" to proceed to the embed code step."]})})]}),"embed"===me&&(0,We.jsx)("div",{className:"mt-4",children:(0,We.jsxs)("div",{className:"flex flex-col lg:flex-row gap-6",children:[(0,We.jsxs)("div",{className:"flex-1 space-y-6 min-w-0 lg:max-w-none",children:[(0,We.jsxs)("div",{className:"border-t border-gray-200 pt-4",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,We.jsx)(Xe.A,{className:"w-5 h-5 text-blue-600"}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Embed Method"})]}),(0,We.jsxs)("div",{className:"mb-4",children:[(0,We.jsxs)("div",{className:"flex gap-4",children:[(0,We.jsxs)("label",{className:"flex items-center",children:[(0,We.jsx)("input",{type:"radio",value:"script",checked:"script"===U,onChange:e=>M(e.target.value),className:"mr-2"}),(0,We.jsx)("span",{className:"text-sm text-gray-700",children:"Script Embed (Recommended)"})]}),(0,We.jsxs)("label",{className:"flex items-center",children:[(0,We.jsx)("input",{type:"radio",value:"iframe",checked:"iframe"===U,onChange:e=>M(e.target.value),className:"mr-2"}),(0,We.jsx)("span",{className:"text-sm text-gray-700",children:"Iframe Embed (For Bubble.io)"})]})]}),"iframe"===U&&(0,We.jsx)("div",{className:"mt-3 p-3 bg-blue-50 rounded-md",children:(0,We.jsxs)("p",{className:"text-xs text-blue-800",children:[(0,We.jsx)("strong",{children:"For Bubble.io:"}),' Use this iframe code in your HTML element set to "Embed as iFrame"']})})]})]}),"script"===U&&(0,We.jsxs)("div",{className:"border-t border-gray-200 pt-4",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,We.jsx)(Xe.A,{className:"w-5 h-5 text-blue-600"}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Configuration"})]}),(0,We.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Container ID"}),(0,We.jsx)("input",{type:"text",value:C,onChange:e=>S(e.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"#faq-widget-container"}),(0,We.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"CSS selector for the container element"})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Theme"}),(0,We.jsxs)("select",{value:D,onChange:e=>P(e.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[(0,We.jsx)("option",{value:"auto",children:"Auto (inherit from site)"}),(0,We.jsx)("option",{value:"light",children:"Light"}),(0,We.jsx)("option",{value:"dark",children:"Dark"})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Display Mode"}),(0,We.jsxs)("select",{value:O,onChange:e=>F(e.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[(0,We.jsx)("option",{value:"full",children:"Full Page"}),(0,We.jsx)("option",{value:"compact",children:"Compact"})]})]})]})]}),"iframe"===U&&(0,We.jsxs)("div",{className:"border-t border-gray-200 pt-4",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,We.jsx)(Xe.A,{className:"w-5 h-5 text-blue-600"}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Iframe Settings"})]}),(0,We.jsxs)("div",{className:"grid grid-cols-2 gap-4",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Width"}),(0,We.jsx)("input",{type:"text",value:J,onChange:e=>q(e.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"100%"})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Height"}),(0,We.jsx)("input",{type:"text",value:Q,onChange:e=>Y(e.target.value),className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"800px"})]})]})]}),"script"===U&&(0,We.jsxs)("div",{className:"border-t border-gray-200 pt-4",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,We.jsx)(et.A,{className:"w-5 h-5 text-blue-600"}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Customization"})]}),(0,We.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Font Family"}),(0,We.jsxs)("select",{value:Re,onChange:e=>{const t=e.target.value;oe(e=>(0,o.A)((0,o.A)({},e),{},{typography:(0,o.A)((0,o.A)({},e.typography),{},{body:(0,o.A)((0,o.A)({},e.typography.body),{},{fontFamily:Le.Jg[t]||Le.Jg.system})})}))},className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[(0,We.jsx)("option",{value:"system",children:"System Default"}),(0,We.jsx)("option",{value:"inter",children:"Inter"}),(0,We.jsx)("option",{value:"roboto",children:"Roboto"}),(0,We.jsx)("option",{value:"open-sans",children:"Open Sans"}),(0,We.jsx)("option",{value:"lato",children:"Lato"}),(0,We.jsx)("option",{value:"montserrat",children:"Montserrat"}),(0,We.jsx)("option",{value:"poppins",children:"Poppins"}),(0,We.jsx)("option",{value:"georgia",children:"Georgia (Serif)"}),(0,We.jsx)("option",{value:"times",children:"Times New Roman (Serif)"}),(0,We.jsx)("option",{value:"monospace",children:"Monospace"})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Font Size"}),(0,We.jsxs)("select",{value:Oe,onChange:e=>{const t=e.target.value;oe(e=>(0,o.A)((0,o.A)({},e),{},{typography:(0,o.A)((0,o.A)({},e.typography),{},{body:(0,o.A)((0,o.A)({},e.typography.body),{},{fontSize:Le.Rh[t]||Le.Rh.medium})})}))},className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:[(0,We.jsx)("option",{value:"small",children:"Small"}),(0,We.jsx)("option",{value:"medium",children:"Medium"}),(0,We.jsx)("option",{value:"large",children:"Large"}),(0,We.jsx)("option",{value:"xlarge",children:"Extra Large"})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Backgroun
1d Color"}),(0,We.jsxs)("div",{className:"flex gap-2",children:[(0,We.jsx)("input",{type:"color",value:re.colors.surface,onChange:e=>oe(t=>(0,o.A)((0,o.A)({},t),{},{colors:(0,o.A)((0,o.A)({},t.colors),{},{surface:(0,De.qw)(e.target.value,t.colors.surface)})})),className:"h-10 w-16 border border-gray-300 rounded-md cursor-pointer"}),(0,We.jsx)("input",{type:"text",value:re.colors.surface,onChange:e=>oe(t=>(0,o.A)((0,o.A)({},t),{},{colors:(0,o.A)((0,o.A)({},t.colors),{},{surface:(0,De.qw)(e.target.value,t.colors.surface)})})),className:"flex-1 px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"#eff6ff"})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Accent Color"}),(0,We.jsxs)("div",{className:"flex gap-2",children:[(0,We.jsx)("input",{type:"color",value:re.colors.primary,onChange:e=>{const t=(0,De.qw)(e.target.value,re.colors.primary);oe(e=>(0,o.A)((0,o.A)({},e),{},{colors:(0,o.A)((0,o.A)({},e.colors),{},{primary:t,primaryHover:(0,Le.zG)(t),focusRing:t})}))},className:"h-10 w-16 border border-gray-300 rounded-md cursor-pointer"}),(0,We.jsx)("input",{type:"text",value:re.colors.primary,onChange:e=>{const t=(0,De.qw)(e.target.value,re.colors.primary);oe(e=>(0,o.A)((0,o.A)({},e),{},{colors:(0,o.A)((0,o.A)({},e.colors),{},{primary:t,primaryHover:(0,Le.zG)(t),focusRing:t})}))},className:"flex-1 px-3 py-2 border border-gray-300 rounded-md text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"#3b82f6"})]})]})]}),Ue&&(0,We.jsx)("p",{className:"text-sm text-red-600 mb-2",role:"alert",children:Ue}),(0,We.jsx)("div",{className:"flex justify-end mt-2",children:(0,We.jsx)("button",{type:"button",onClick:async()=>{if(!s||!r)return void Ie.Ay.error("A public share link is required to save theme settings.");const e=Nt(re);if(e.ok){de(!0);try{var t;const e=(0,B.doc)(G.db,"shareableLinks",s),n=Fe(null===(t=(await(0,B.getDoc)(e)).data())||void 0===t?void 0:t.shareBranding);await(0,B.mZ)(e,{shareBranding:(0,o.A)((0,o.A)({},n),{},{workspaceTheme:re})}),Ie.Ay.success("Theme saved to your share link.")}catch(n){console.error(n),Ie.Ay.error(n.message||"Failed to save theme.")}finally{de(!1)}}else Ie.Ay.error(e.message||"Primary color does not meet contrast requirements.")},disabled:le||!s||!!Ue,className:"inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md bg-brand text-brand-on border border-transparent hover:bg-brand-hover disabled:opacity-50 disabled:cursor-not-allowed",children:le?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Se.y$,{size:"sm",className:"mr-1"}),"Saving\u2026"]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)($e.A,{className:"w-4 h-4 mr-1"}),"Save theme to share link"]})})})]}),(0,We.jsxs)("div",{children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700",children:"Embed Code"}),(0,We.jsx)("button",{onClick:()=>{h&&(navigator.clipboard.writeText(h),A(!0),setTimeout(()=>A(!1),2e3))},disabled:!h,className:"inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-md ".concat(k?"bg-green-50 text-green-700 border border-green-200":"bg-gray-50 text-gray-700 border border-gray-200 hover:bg-gray-100"," ").concat(h?"":"opacity-50 cursor-not-allowed"),children:k?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(d.A,{className:"w-4 h-4 mr-1"}),"Copied!"]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(w.A,{className:"w-4 h-4 mr-1"}),"Copy"]})})]}),(0,We.jsx)("textarea",{value:h,readOnly:!0,rows:8,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm font-mono focus:outline-none focus:ring-2 focus:ring-blue-500 bg-gray-50",style:{fontFamily:"monospace",fontSize:"0.875rem"}})]}),(0,We.jsxs)("div",{className:"p-4 bg-blue-50 rounded-md",children:[(0,We.jsx)("h4",{className:"text-sm font-medium text-blue-900 mb-2",children:"How to use:"}),"script"===U?(0,We.jsxs)("ol",{className:"text-sm text-blue-800 space-y-1 list-decimal list-inside",children:[(0,We.jsx)("li",{children:"Copy the embed code above"}),(0,We.jsx)("li",{children:"Paste it into your website's HTML where you want the FAQ widget to appear"}),(0,We.jsx)("li",{children:"The widget will automatically load and display FAQs from your knowledge base"}),(0,We.jsx)("li",{children:"FAQ schema will be automatically injected for SEO"})]}):(0,We.jsxs)("ol",{className:"text-sm text-blue-800 space-y-1 list-decimal list-inside",children:[(0,We.jsx)("li",{children:"Copy the iframe code above"}),(0,We.jsx)("li",{children:"In Bubble.io, add an HTML element"}),(0,We.jsx)("li",{children:'Set the HTML element to "Embed as iFrame"'}),(0,We.jsx)("li",{children:"Paste the iframe code into the HTML element"}),(0,We.jsx)("li",{children:"The FAQ page will load in the iframe"})]})]}),(0,We.jsxs)("div",{className:"p-4 bg-green-50 rounded-md",children:[(0,We.jsxs)("h4",{className:"text-sm font-medium text-green-900 mb-2 flex items-center gap-2",children:[(0,We.jsx)(tt.A,{className:"w-4 h-4"}),"SEO Benefits"]}),"script"===U?(0,We.jsxs)("ul",{className:"text-sm text-green-800 space-y-1 list-disc list-inside",children:[(0,We.jsx)("li",{children:"FAQ content appears as part of your website (not external link)"}),(0,We.jsx)("li",{children:"Automatic FAQ schema markup for Google rich results"}),(0,We.jsx)("li",{children:"Content is indexed by search engines on your domain"}),(0,We.jsx)("li",{children:"Improved search visibility with FAQ rich snippets"})]}):(0,We.jsxs)("ul",{className:"text-sm text-green-800 space-y-1 list-disc list-inside",children:[(0,We.jsx)("li",{children:"SEO helper script automatically injects FAQ schema into your page"}
1),(0,We.jsx)("li",{children:"FAQ schema appears in your page's HTML for search engines"}),(0,We.jsx)("li",{children:"Note: Script embed method provides better SEO (content is native to your domain)"}),(0,We.jsx)("li",{children:"Iframe content is still indexed, but may be treated as separate from your main page"})]})]})]}),"script"===U&&fe.length>0&&(0,We.jsx)("div",{className:"w-full lg:w-1/2 border-t lg:border-t-0 lg:border-l border-gray-200 pt-6 lg:pt-0 lg:pl-6 flex-shrink-0",children:(0,We.jsxs)("div",{className:"sticky top-4",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 mb-4",children:[(0,We.jsx)(tt.A,{className:"w-5 h-5 text-blue-600"}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Live Preview"})]}),(0,We.jsxs)("div",{className:"border border-gray-300 rounded-lg overflow-hidden bg-white shadow-lg",style:{maxHeight:"calc(100vh - 200px)",overflowY:"auto"},children:[(0,We.jsx)("div",{dangerouslySetInnerHTML:{__html:Me}}),(0,We.jsx)(bt,{workspaceId:r,linkId:s,containerId:"embed-preview-container",workspaceTheme:re,theme:D,displayMode:O,isInternalSetup:!0})]})]})})]})})]})})}),(0,We.jsx)("div",{className:"px-4 py-3 bg-gray-50 sm:px-6 sm:flex sm:flex-row-reverse",children:(0,We.jsx)("button",{type:"button",onClick:n,className:"inline-flex justify-center w-full px-4 py-2 text-base font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm",children:"Close"})})]})]})}):null};var St=n(15003),Et=n(62839);const It=e=>{var t;let n=e.isOpen,r=e.onClose,s=e.onMarkAsSeen;const l=(0,i.useState)([]),d=(0,a.A)(l,2),u=d[0],g=d[1],h=(0,i.useState)(!0),f=(0,a.A)(h,2),y=f[0],v=f[1],x=(0,i.useState)(null),b=(0,a.A)(x,2),w=b[0],k=b[1],A=(0,i.useState)(null),j=(0,a.A)(A,2),N=j[0],C=j[1],S=(0,i.useState)(""),E=(0,a.A)(S,2),I=E[0],D=E[1],P=(0,i.useState)(null),T=(0,a.A)(P,2),R=T[0],O=T[1],F=(0,i.useState)(new Set),L=(0,a.A)(F,2),_=L[0],U=L[1],M=(0,he.xI)(),z=(0,i.useRef)(s);z.current=s;const V="[email protected]"===(null===(t=M.currentUser)||void 0===t?void 0:t.email);(0,i.useEffect)(()=>{if(!n)return;(async()=>{try{v(!0),k(null);const e=(0,B.rJ)(G.db,"appUpdates"),t=(0,B.P)(e,(0,B.My)("versionNumber","desc"),(0,B.AB)(50)),n=(await(0,B.GG)(t)).docs.map(e=>(0,o.A)({id:e.id},e.data()));if(g(n),(0,W.gg)("Fetched app updates:",n),M.currentUser){const e="lastSeenUpdateVersion-".concat(M.currentUser.uid),t=localStorage.getItem(e),r=e=>{if(!e)return 0;const t=e.split(".");if(3!==t.length)return 0;return(parseInt(t[0],10)||0)+.1*(parseInt(t[1],10)||0)+.001*(parseInt(t[2],10)||0)},o=new Set;if(t){const e=r(t);n.forEach(t=>{(t.versionNumber||r(t.version))<=e&&o.add(t.version)})}if(U(o),n.length>0){const t=n[0];localStorage.setItem(e,t.version);const r=z.current;r&&r(t.version)}}}catch(e){console.error("Error fetching app updates:",e),k("Failed to load updates. Please try again later.")}finally{v(!1)}})()},[n]);if(!n)return null;const J=e=>{if(!e)return"";return(e.toDate?e.toDate():new Date(e)).toLocaleDateString("en-US",{year:"numeric",month:"long",day:"numeric"})},q=()=>{C(null),D("")};return(0,We.jsxs)("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:[(0,We.jsxs)("div",{className:"flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:block sm:p-0",children:[(0,We.jsx)("div",{className:"fixed inset-0 transition-opacity bg-gray-500 bg-opacity-75",onClick:r}),(0,We.jsx)("div",{className:"inline-block overflow-hidden text-left align-bottom transition-all transform bg-white rounded-lg shadow-xl sm:my-8 sm:align-middle sm:max-w-2xl sm:w-full",children:(0,We.jsx)("div",{className:"px-4 pt-5 pb-4 bg-white sm:p-6 sm:pb-4",children:(0,We.jsx)("div",{className:"sm:flex sm:items-start",children:(0,We.jsxs)("div",{className:"mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left w-full",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,We.jsxs)("div",{className:"flex items-center gap-3",children:[(0,We.jsx)(ct.A,{className:"w-6 h-6 text-blue-600"}),(0,We.jsx)("h3",{className:"text-lg font-medium leading-6 text-gray-900",children:"What's New"})]}),(0,We.jsx)("button",{onClick:r,className:"text-gray-400 hover:text-gray-500 focus:outline-none",children:(0,We.jsx)(c.A,{className:"w-6 h-6"})})]}),(0,We.jsx)("div",{className:"mt-4",children:y?(0,We.jsxs)("div",{className:"text-center py-8",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-600"}),(0,We.jsx)("p",{className:"mt-2 text-sm text-gray-500",children:"Loading updates..."})]}):w?(0,We.jsx)("div",{className:"p-4 bg-red-50 rounded-md",children:(0,We.jsx)("p",{className:"text-sm text-red-700",children:w})}):0===u.length?(0,We.jsx)("div",{className:"text-center py-8",children:(0,We.jsx)("p",{className:"text-sm text-gray-500",children:"No updates available yet."})}):(0,We.jsx)("div",{className:"space-y-6 max-h-[60vh] overflow-y-auto pr-2",children:u.map((e,t)=>{const n=(e=>!!M.currentUser&&!_.has(e.version))(e);return(0,We.jsxs)("div",{className:"border-b border-gray-200 pb-4 last:border-b-0 rounded-lg p-3 ".concat(n?"bg-yellow-50 border-yellow-200":""),children:[(0,We.jsx)("div",{className:"flex items-start justify-between mb-2",children:(0,We.jsxs)("div",{className:"flex-1",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsx)("h4",{className:"text-base font-semibold text-gray-900",children:(r=e.version,a=e.beta,a?"Beta ".concat(r):r)}),V&&N!==e.id&&(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(0,We.jsx)("button",{onClick:()=>(e=>{C(e.id),D(e.summary)})(e),className:"p-1 text-gray-400 hover:text-blue-600 transition-colors",title:"Edit update",children:(0,We.jsx)(m.A,{className:"w-4 h-4"})}),(0,We.jsx)("button",{onClick:()=>O(e.id),className:"p-1 text-gray-400 hover:text-red-600 transition-colors",title:"Delete update",children:(0,We.jsx)(p.A,{className:"w-4 h-4"})})]})]}),e.createdAt&&(0,We.jsx)("span",{className:"text-xs text-gray-500",children:J(e.createdAt)})]})}),N===e.id?(0,We.jsxs)("div",{className:"space-y-2",children:[(0,We.jsx)("textarea",{value:I,onChange:e=>D(e.target.value),className:"w-full p-2 border border-gray-300 rounded-md text-sm text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500",rows:3}),(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(0,We.jsx)(St.A,{type:"button",size:"sm",onClick:()=>(async e=>{try{await(0,Et.y3)(e,{summary:I}),g(u.map(t=>
1t.id===e?(0,o.A)((0,o.A)({},t),{},{summary:I}):t)),C(null),D(""),Ie.Ay.success("Update saved successfully")}catch(w){console.error("Error saving update:",w),Ie.Ay.error("Failed to save update")}})(e.id),leadingIcon:(0,We.jsx)($e.A,{className:"w-3 h-3"}),className:"flex items-center gap-1 px-3 py-1 text-sm rounded-md transition-colors",children:"Save"}),(0,We.jsxs)("button",{onClick:q,className:"flex items-center gap-1 px-3 py-1 text-sm text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors",children:[(0,We.jsx)(c.A,{className:"w-3 h-3"}),"Cancel"]})]})]}):(0,We.jsx)("p",{className:"text-sm text-gray-700 leading-relaxed",children:e.summary})]},e.id);var r,a})})}),(0,We.jsx)("div",{className:"mt-6 flex justify-end",children:(0,We.jsx)("button",{onClick:r,className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500",children:"Close"})})]})})})})]}),R&&(0,We.jsx)("div",{className:"fixed inset-0 z-[60] flex items-center justify-center bg-black bg-opacity-50",children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-xl p-6 max-w-md w-full mx-4",children:[(0,We.jsx)("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"Delete Update?"}),(0,We.jsx)("p",{className:"text-sm text-gray-600 mb-4",children:"Are you sure you want to delete this update? This action cannot be undone."}),(0,We.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,We.jsx)("button",{onClick:()=>O(null),className:"px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50",children:"Cancel"}),(0,We.jsx)("button",{onClick:()=>(async e=>{try{await(0,Et._2)(e),g(u.filter(t=>t.id!==e)),O(null),Ie.Ay.success("Update deleted successfully")}catch(w){console.error("Error deleting update:",w),Ie.Ay.error("Failed to delete update")}})(R),className:"px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-md",children:"Delete"})]})]})})]})};var Dt=n(63557),Pt=n(5244),Tt=n(84259),Rt=n(94965);function Ot(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const o of e){var r;if(!o||"object"!==typeof o)continue;const e="string"===typeof o.id?o.id.trim():"",a="string"===typeof o.name?o.name.trim():"";if(!e||!a||t.has(e))continue;t.add(e);let i=null;"number"===typeof o.createdAt&&Number.isFinite(o.createdAt)?i=o.createdAt:o.createdAt&&"function"===typeof o.createdAt.toMillis?i=o.createdAt.toMillis():"number"===typeof(null===(r=o.createdAt)||void 0===r?void 0:r.seconds)&&(i=1e3*o.createdAt.seconds),n.push({id:e,name:a,createdAt:i})}return n}function Ft(e){if(!e||"string"!==typeof e.folderId)return null;return e.folderId.trim()||null}function Lt(e,t){const n=Ft(e);if(!n)return null;const r=Ot(t).find(e=>e.id===n);return(null===r||void 0===r?void 0:r.name)||null}function _t(e,t){const n=e&&"object"===typeof e?e:{},r=t&&"object"===typeof t?t:{},o=Object.keys(n),a=Object.keys(r);if(o.length!==a.length)return!1;for(const i of o){if(!Object.prototype.hasOwnProperty.call(r,i))return!1;if(n[i]!==r[i])return!1}return!0}function Ut(e,t){const n=e&&"object"===typeof e?e:{};if(!t||0===t.length)return 0===Object.keys(n).length?n:{};const r={};for(const o of t)Object.prototype.hasOwnProperty.call(n,o)&&(r[o]=n[o]);return _t(n,r)?n:r}function Mt(e,t,n,r){const a=e&&"object"===typeof e?e:{},i=(0,o.A)((0,o.A)({},a),{},{[t]:n}),s={};for(const o of r||[])Object.prototype.hasOwnProperty.call(i,o)&&(s[o]=i[o]);return _t(a,s)?a:s}function zt(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return!!e&&(!0===e.isExternalWorkspace||!(!t||!e.organizationId||e.organizationId===t))}function Bt(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};if(e&&zt(e,arguments.length>5&&void 0!==arguments[5]?arguments[5]:null))return 0;return function(e){let t=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return null==e?0:((arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})[e]||0)+(t[e]||0)+(n[e]||0)}(null!==t&&void 0!==t?t:null===e||void 0===e?void 0:e.id,n,r,o)}function Wt(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return Array.isArray(e)?e.filter(e=>!zt(e,t)).map(e=>e.id):[]}const Vt=e=>{const t=(0,i.useState)({}),n=(0,a.A)(t,2),r=n[0],o=n[1],s=(0,i.useRef)([]);return(0,i.useEffect)(()=>{const t=e||[],n=s.current;if(!(t.length!==n.length||t.some((e,t)=>e!==n[t]))&&n.length>0)return;if(s.current=t,!t||0===t.length)return void o({});o(e=>Ut(e,t));const r=[];
1return t.forEach(e=>{try{const n=(0,B.rJ)(G.db,"workspaces",e,"chatLogs"),a=(0,B.P)(n,(0,B._M)("unread","==",!0)),i=(0,B.aQ)(a,n=>{const r=n.docs.filter(e=>{const t=e.data();return!0!==t.archived&&!0===t.unread&&!0!==t.isFAQ&&!0!==t.isInternalSetup}).length;o(n=>Mt(n,e,r,t))},n=>{console.error("Error with unread chats listener for ".concat(e,":"),n),o(n=>Mt(n,e,0,t))});r.push(i)}catch(n){console.error("Failed to set up listener for workspace ".concat(e,":"),n)}}),()=>{r.forEach(e=>{try{e()}catch(t){console.error("Error unsubscribing:",t)}})}},[null===e||void 0===e?void 0:e.join(",")]),r},Jt=e=>{const t=(0,i.useState)({}),n=(0,a.A)(t,2),r=n[0],o=n[1],s=(0,i.useRef)([]);return(0,i.useEffect)(()=>{const t=e||[],n=s.current;if(!(t.length!==n.length||t.some((e,t)=>e!==n[t]))&&n.length>0)return;if(s.current=t,!t||0===t.length)return void o({});o(e=>Ut(e,t));const r=[];return t.forEach(e=>{try{const n=(0,B.rJ)(G.db,"shareableLinks"),a=(0,B.P)(n,(0,B._M)("workspaceId","==",e),(0,B._M)("analytics.unreadSessions",">",0)),i=(0,B.aQ)(a,n=>{const r=n.docs.reduce((e,t)=>{var n;const r=t.data()||{};return!0===r.archived?e:e+((null===(n=r.analytics)||void 0===n?void 0:n.unreadSessions)||0)},0);o(n=>Mt(n,e,r,t))},n=>{console.error("Error with unread share views listener for ".concat(e,":"),n),o(n=>Mt(n,e,0,t))});r.push(i)}catch(n){console.error("Failed to set up share views listener for workspace ".concat(e,":"),n)}}),()=>{r.forEach(e=>{try{e()}catch(t){}})}},[null===e||void 0===e?void 0:e.join(",")]),r},qt={"Smileys & People":["\ud83d\ude00","\ud83d\ude03","\ud83d\ude04","\ud83d\ude01","\ud83d\ude06","\ud83d\ude05","\ud83e\udd23","\ud83d\ude02","\ud83d\ude42","\ud83d\ude43","\ud83d\ude09","\ud83d\ude0a","\ud83d\ude07","\ud83e\udd70","\ud83d\ude0d","\ud83e\udd29","\ud83d\ude18","\ud83d\ude17","\ud83d\ude1a","\ud83d\ude19","\ud83d\ude0b","\ud83d\ude1b","\ud83d\ude1c","\ud83e\udd2a","\ud83d\ude1d","\ud83e\udd11","\ud83e\udd17","\ud83e\udd2d","\ud83e\udd2b","\ud83e\udd14","\ud83e\udd10","\ud83e\udd28","\ud83d\ude10","\ud83d\ude11","\ud83d\ude36","\ud83d\ude0f","\ud83d\ude12","\ud83d\ude44","\ud83d\ude2c","\ud83e\udd25","\ud83d\ude0c","\ud83d\ude14","\ud83d\ude2a","\ud83e\udd24","\ud83d\ude34","\ud83d\ude37","\ud83e\udd12","\ud83e\udd15","\ud83e\udd22","\ud83e\udd2e","\ud83e\udd27","\ud83e\udd75","\ud83e\udd76","\ud83d\ude36\u200d\ud83c\udf2b\ufe0f","\ud83d\ude35","\ud83d\ude35\u200d\ud83d\udcab","\ud83e\udd2f","\ud83e\udd20","\ud83e\udd73","\ud83d\ude0e","\ud83e\udd13","\ud83e\uddd0","\ud83d\ude15","\ud83d\ude1f","\ud83d\ude41","\u2639\ufe0f","\ud83d\ude2e","\ud83d\ude2f","\ud83d\ude32","\ud83d\ude33","\ud83e\udd7a","\ud83d\ude26","\ud83d\ude27","\ud83d\ude28","\ud83d\ude30","\ud83d\ude25","\ud83d\ude22","\ud83d\ude2d","\ud83d\ude31","\ud83d\ude16","\ud83d\ude23","\ud83d\ude1e","\ud83d\ude13","\ud83d\ude29","\ud83d\ude2b","\ud83e\udd71","\ud83d\ude24","\ud83d\ude21","\ud83d\ude20","\ud83e\udd2c","\ud83d\ude08","\ud83d\udc7f","\ud83d\udc80","\u2620\ufe0f","\ud83d\udca9","\ud83e\udd21","\ud83d\udc79","\ud83d\udc7a","\ud83d\udc7b","\ud83d\udc7d","\ud83d\udc7e","\ud83e\udd16","\ud83d\ude3a","\ud83d\ude38","\ud83d\ude39","\ud83d\ude3b","\ud83d\ude3c","\ud83d\ude3d","\ud83d\ude40","\ud83d\ude3f","\ud83d\ude3e"],"Gestures & Body Parts":["\ud83d\udc4b","\ud83e\udd1a","\ud83d\udd90","\u270b","\ud83d\udd96","\ud83d\udc4c","\ud83e\udd0c","\ud83e\udd0f","\u270c\ufe0f","\ud83e\udd1e","\ud83e\udd1f","\ud83e\udd18","\ud83e\udd19","\ud83d\udc48","\ud83d\udc49","\ud83d\udc46","\ud83d\udd95","\ud83d\udc47","\u261d\ufe0f","\ud83d\udc4d","\ud83d\udc4e","\u270a","\ud83d\udc4a","\ud83e\udd1b","\ud83e\udd1c","\ud83d\udc4f","\ud83d\ude4c","\ud83d\udc50","\ud83e\udd32","\ud83e\udd1d","\ud83d\ude4f","\u270d\ufe0f","\ud83d\udcaa","\ud83e\uddbe","\ud83e\uddbf","\ud83e\uddb5","\ud83e\uddb6","\ud83d\udc42","\ud83e\uddbb","\ud83d\udc43","\ud83e\udde0","\ud83e\udec0","\ud83e\udec1","\ud83e\uddb7","\ud83e\uddb4","\ud83d\udc40","\ud83d\udc41\ufe0f","\ud83d\udc45","\ud83d\udc44"],"People & Fantasy":["\ud83d\udc76","\ud83e\uddd2","\ud83d\udc66","\ud83d\udc67","\ud83e\uddd1","\ud83d\udc71","\ud83d\udc68","\ud83e\uddd4","\ud83d\udc68\u200d\ud83e\uddb0","\ud83d\udc68\u200d\ud83e\uddb1","\ud83d\udc68\u200d\ud83e\uddb3","\ud83d\udc68\u200d\ud83e\uddb2","\ud83d\udc69","\ud83d\udc69\u200d\ud83e\uddb0","\ud83e\uddd1\u200d\ud83e\uddb0","\ud83d\udc69\u200d\ud83e\uddb1","\ud83e\uddd1\u200d\ud83e\uddb1","\ud83d\udc69\u200d\ud83e\uddb3","\ud83e\uddd1\u200d\ud83e\uddb3","\ud83d\udc69\u200d\ud83e\uddb2","\ud83e\uddd1\u200d\ud83e\uddb2","\ud83d\udc71\u200d\u2640\ufe0f","\ud83d\udc71\u200d\u2642\ufe0f","\ud83e\uddd3","\ud83d\udc74","\ud83d\udc75","\ud83d\ude4d","\ud83d\ude4d\u200d\u2642\ufe0f","\ud83d\ude4d\u200d\u2640\ufe0f","\ud83d\ude4e","\ud83d\ude4e\u200d\u2642\ufe0f","\ud83d\ude4e\u200d\u2640\ufe0f","\ud83d\ude45","\ud83d\ude45\u200d\u2642\ufe0f","\ud83d\ude45\u200d\u2640\ufe0f","\ud83d\ude46","\ud83d\ude46\u200d\u2642\ufe0f","\ud83d\ude46\u200d\u2640\ufe0f","\ud83d\udc81","\ud83d\udc81\u200d\u2642\ufe0f","\ud83d\udc81\u200d\u2640\ufe0f","\ud83d\ude4b","\ud83d\ude4b\u200d\u2642\ufe0f","\ud83d\ude4b\u200d\u2640\ufe0f","\ud83e\uddcf","\ud83e\uddcf\u200d\u2642\ufe0f","\ud83e\uddcf\u200d\u2640\ufe0f","\ud83e\udd26","\ud83e\udd26\u200d\u2642\ufe0f","\ud83e\udd26\u200d\u2640\ufe0f","\ud83e\udd37","\ud83e\udd37\u200d\u2642\ufe0f","\ud83e\udd37\u200d\u2640\ufe0f","\ud83d\ude47","\ud83d\ude47\u200d\u2642\ufe0f","\ud83d\ude47\u200d\u2640\ufe0f","\ud83e\udd26","\ud83e\udd26\u200d\u2642\ufe0f","\ud83e\udd26\u200d\u2640\ufe0f","\ud83e\udd37","\ud83e\udd37\u200d\u2642\ufe0f","\ud83e\udd37\u200d\u2640\ufe0f","\ud83e\uddd1\u200d\u2695\ufe0f","\ud83d\udc68\u200d\u2695\ufe0f","\ud83d\udc69\u200d\u2695\ufe0f","\ud83e\uddd1\u200d\ud83c\udf93","\ud83d\udc68\u200d\ud83c\udf93","\ud83d\udc69\u200d\ud83c\udf93","\ud83e\uddd1\u200d\ud83c\udfeb","\ud83d\udc68\u200d\ud83c\udfeb","\ud83d\udc69\u200d\ud83c\udfeb","\ud83e\uddd1\u200d\u2696\ufe0f","\ud83d\udc68\u200d\u2696\ufe0f","\ud83d\udc69\u200d\u2696\ufe0f","\ud83e\uddd1\u200d\ud83c\udf3e","\ud83d\udc68\u200d\ud83c\udf3e","\ud83d\udc69\u200d\ud83c\udf3e","\ud83e\uddd1\u200d\ud83c\udf73","\ud83d\udc68\u200d\ud83c\udf73","\ud83d\udc69\u200d\ud83c\udf73","\ud83e\uddd1\u200d\ud83d\udd27","\ud83d\udc68\u200d\ud83d\udd27","\ud83d\udc69\u200d\ud83d\udd27","\ud83e\uddd1\u200d\ud83c\udfed","\ud83d\udc68\u200d\ud83c\udfed","\ud83d\udc69\u200d\ud83c\udfed","\ud83e\uddd1\u200d\ud83d\udcbc","\ud83d\udc68\u200d\ud83d\udcbc","\ud83d\udc69\u200d\ud83d\udcbc","\ud83e\uddd1\u200d\ud83d\udd2c","\ud83d\udc68\u200d\ud83d\udd2c","\ud83d\udc69\u200d\ud83d\udd2c","\ud83e\uddd1\u200d\ud83d\udcbb","\ud83d\udc68\u200d\ud83d\udcbb","\ud83d\udc69\u200d\ud83d\udcbb","\ud83e\uddd1\u200d\ud83c\udfa4","\ud83d\udc68\u200d\ud83c\udfa4","\ud83d\udc69\u200d\ud83c\udfa4","\ud83e\uddd1\u200d\ud83c\udfa8","\ud83d\udc68\u200d\ud83c\udfa8","\ud83d\udc69\u200d\ud83c\udfa8","\ud83e\uddd1\u200d\u2708\ufe0f","\ud83d\udc68\u200d\u2708\ufe0f","\ud83d\udc69\u200d\u2708\ufe0f","\ud83e\uddd1\u200d\ud83d\ude80","\ud83d\udc68\u200d\ud83d\ude80","\ud83d\udc69\u200d\ud83d\ude80","\ud83e\uddd1\u200d\ud83d\ude92","\ud83d\udc68\u200d\ud83d\ude92","\ud83d\udc69\u200d\ud83d\ude92","\ud83d\udc6e","\ud83d\udc6e\u200d\u2642\ufe0f","\ud83d\udc6e\u200d\u2640\ufe0f","\ud83d\udd75\ufe0f","\ud83d\udd75\ufe0f\u200d\u2642\ufe0f","\ud83d\udd75\ufe0f\u200d\u2640\ufe0f","\ud83d\udc82","\ud83d\udc82\u200d\u2642\ufe0f","\ud83d\udc82\u200d\u2640\ufe0f","\ud83e\udd77","\ud83d\udc77","\ud83d\udc77\u200d\u2642\ufe0f","\ud83d\udc77\u200d\u2640\ufe0f","\ud83e\udd34","\ud83d\udc78","\ud83d\udc73","\ud83d\udc73\u200d\u2642\ufe0f","\ud83d\udc73\u200d\u2640\ufe0f","\ud83d\udc72","\ud83e\uddd5","\ud83e\udd35","\ud83e\udd35\u200d\u2642\ufe0f","\ud83e\udd35\u200d\u2640\ufe0f","\ud83d\udc70","\ud83d\udc70\u200d\u2642\ufe0f","\ud83d\udc70\u200d\u2640\ufe0f","\ud83e\udd30","\ud83e\udd31","\ud83d\udc7c","\ud83c\udf85","\ud83e\udd36","\ud83e\uddb8","\ud83e\uddb8\u200d\u2642\ufe0f","\ud83e\uddb8\u200d\u2640\ufe0f","\ud83e\uddb9","\ud83e\uddb9\u200d\u2642\ufe0f","\ud83e\uddb9\u200d\u2640\ufe0f","\ud83e\uddd9","\ud83e\uddd9\u200d\u2642\ufe0f","\ud83e\uddd9\u200d\u2640\ufe0f","\ud83e\uddda","\ud83e\uddda\u200d\u2642\ufe0f","\ud83e\uddda\u200d\u2640\ufe0f","\ud83e\udddb","\ud83e\udddb\u200d\u2642\ufe0f","\ud83e\udddb\u200d\u2640\ufe0f","\ud83e\udddc","\ud83e\udddc\u200d\u2642\ufe0f","\ud83e\udddc\u200d\u2640\ufe0f","\ud83e\udddd","\ud83e\udddd\u200d\u2642\ufe0f","\ud83e\udddd\u200d\u2640\ufe0f","\ud83e\uddde","\ud83e\uddde\u200d\u2642\ufe0f","\ud83e\uddde\u200d\u2640\ufe0f","\ud83e\udddf","\ud83e\udddf\u200d\u2642\ufe0f","\ud83e\udddf\u200d\u2640\ufe0f","\ud83d\udc86","\ud83d\udc86\u200d\u2642\ufe0f","\ud83d\udc86\u200d\u2640\ufe0f","\ud83d\udc87","\ud83d\udc87\u200d\u2642\ufe0f","\ud83d\udc87\u200d\u2640\ufe0f","\ud83d\udeb6","\ud83d\udeb6\u200d\u2642\ufe0f","\ud83d\udeb6\u200d\u2640\ufe0f","\ud83e\uddcd","\ud83e\uddcd\u200d\u2642\ufe0f","\ud83e\uddcd\u200d\u2640\ufe0f","\ud83e\uddce","\ud83e\uddce\u200d\u2642\ufe0f","\ud83e\uddce\u200d\u2640\ufe0f","\ud83c\udfc3","\ud83c\udfc3\u200d\u2642\ufe0f","\ud83c\udfc3\u200d\u2640\ufe0f","\ud83d\udc83","\ud83d\udd7a","\ud83d\udd74\ufe0f","\ud83d\udc6f","\ud83d\udc6f\u200d\u2642\ufe0f","\ud83d\udc6f\u200d\u2640\ufe0f","\ud83e\uddd8","\ud83e\uddd8\u200d\u2642\ufe0f","\ud83e\uddd8\u200d\u2640\ufe0f","\ud83d\udec0","\ud83d\udecc","\ud83d\udc6d","\ud83d\udc6b","\ud83d\udc6c","\ud83d\udc8f","\ud83d\udc91","\ud83d\udc6a","\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67","\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67","\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66","\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67","\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66","\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66","\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67","\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67","\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc67","\ud83d\udc69\u200d\ud83d\udc66","\ud83d\udc69\u200d\ud83d\udc67","\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66","\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66","\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67","\ud83d\udc68\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc67","\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66","\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc67"],"Animals & Nature":["\ud83d\udc36","\ud83d\udc31","\ud83d\udc2d","\ud83d\udc39","\ud83d\udc30","\ud83e\udd8a","\ud83d\udc3b","\ud83d\udc3c","\ud83d\udc28","\ud83d\udc2f","\ud83e\udd81","\ud83d\udc2e","\ud83d\udc37","\ud83d\udc3d","\ud83d\udc38","\ud83d\udc35","\ud83d\ude48","\ud83d\ude49","\ud83d\ude4a","\ud83d\udc12","\ud83d\udc14","\ud83d\udc27","\ud83d\udc26","\ud83d\udc24","\ud83d\udc23","\ud83d\udc25","\ud83e\udd86","\ud83e\udd85","\ud83e\udd89","\ud83e\udd87","\ud83d\udc3a","\ud83d\udc17","\ud83d\udc34","\ud83e\udd84","\ud83d\udc1d","\ud83d\udc1b","\ud83e\udd8b","\ud83d\udc0c","\ud83d\udc1e","\ud83d\udc1c","\ud83e\udd9f","\ud83e\udd97","\ud83d\udd77\ufe0f","\ud83d\udd78\ufe0f","\ud83e\udd82","\ud83d\udc22","\ud83d\udc0d","\ud83e\udd8e","\ud83e\udd96","\ud83e\udd95","\ud83d\udc19","\ud83e\udd91","\ud83e\udd90","\ud83e\udd9e","\ud83e\udd80","\ud83d\udc21","\ud83d\udc20","\ud83d\udc1f","\ud83d\udc2c","\ud83d\udc33","\ud83d\udc0b","\ud83e\udd88","\ud83d\udc0a","\ud83d\udc05","\ud83d\udc06","\ud83e\udd93","\ud83e\udd8d","\ud83e\udda7","\ud83d\udc18","\ud83e\udd9b","\ud83e\udd8f","\ud83d\udc2a","\ud83d\udc2b","\ud83e\udd92","\ud83e\udd98","\ud83e\udda1","\ud83d\udc03","\ud83d\udc02","\ud83d\udc04","\ud83d\udc0e","\ud83d\udc16","\ud83d\udc0f","\ud83d\udc11","\ud83e\udd99","\ud83d\udc10","\ud83e\udd8c","\ud83d\udc15","\ud83d\udc29","\ud83d\udc08","\ud83d\udc13","\ud83e\udd83","\ud83e\udd9a","\ud83e\udd9c","\ud83e\udda2","\ud83e\udda9","\ud83d\udd4a\ufe0f","\ud83d\udc07","\ud83e\udd9d","\ud83e\udda8","\ud83e\udda6","\ud83e\udda5","\ud83d\udc01","\ud83d\udc00","\ud83d\udc3f\ufe0f","\ud83e\udd94","\ud83c\udf32","\ud83c\udf33","\ud83c\udf34","\ud83c\udf35","\ud83c\udf36\ufe0f","\ud83c\udf3e","\ud83c\udf3f","\u2618\ufe0f","\ud83c\udf40","\ud83c\udf41","\ud83c\udf42","\ud83c\udf43","\ud83c\udf3a","\ud83c\udf3b","\ud83c\udf39","\ud83c\udf37","\ud83c\udf3c","\ud83c\udf38","\ud83c\udf3e","\ud83c\udf31","\ud83c\udf3f","\ud83c\udf43","\ud83c\udf42","\ud83c\udf41","\ud83c\udf44","\ud83c\udf30","\ud83e\udd80","\ud83e\udd9e","\ud83e\udd90","\ud83e\udd91","\ud83c\udf0d","\ud83c\udf0e","\ud83c\udf0f","\ud83c\udf10","\ud83d\uddfe","\ud83e\udded","\ud83c\udfd4\ufe0f","\u26f0\ufe0f","\ud83c\udf0b","\ud83d\uddfb","\ud83c\udfd5\ufe0f","\ud83c\udfd6\ufe0f","\ud83c\udfdc\ufe0f","\ud83c\udfdd\ufe0f","\ud83c\udfde\ufe0f","\ud83c\udfdf\ufe0f","\ud83c\udfdb\ufe0f","\ud83c\udfd7\ufe0f","\ud83e\uddf1","\ud83c\udfd8\ufe0f","\ud83c\udfda\ufe0f","\ud83c\udfe0","\ud83c\udfe1","\ud83c\udfe2","\ud83c\udfe3","\ud83c\udfe4","\ud83c\udfe5","\ud83c\udfe6","\ud83c\udfe8","\ud83c\udfe9","\ud83c\udfea","\ud83c\udfeb","\ud83c\udfec","\ud83c\udfed","\ud83c\udfef","\ud83c\udff0","\ud83d\udc92","\ud83d\uddfc","\ud83d\uddfd","\u26ea","\ud83d\udd4c","\ud83d\uded5","\ud83d\udd4d","\u26e9\ufe0f","\ud83d\udd4b","\u26f2","\u26fa","\ud83c\udf01","\ud83c\udf03","\ud83c\udfd9\ufe0f","\ud83c\udf04","\ud83c\udf05","\ud83c\udf06","\ud83c\udf07","\ud83c\udf09","\u2668\ufe0f","\ud83c\udfa0","\ud83c\udfa1","\ud83c\udfa2","\ud83d\udc88","\ud83c\udfaa","\ud83d\ude82","\ud83d\ude83","\ud83d\ude84","\ud83d\ude85","\ud83d\ude86","\ud83d\ude87","\ud83d\ude88","\ud83d\ude89","\ud83d\ude8a","\ud83d\ude9d","\ud83d\ude9e","\ud83d\ude8b","\ud83d\ude8c","\ud83d\ude8d","\ud83d\ude8e","\ud83d\ude90","\ud83d\ude91","\ud83d\ude92","\ud83d\ude93","\ud83d\ude94","\ud83d\ude95","\ud83d\ude96","\ud83d\ude97","\ud83d\ude98","\ud83d\ude99","\ud83d\ude9a","\ud83d\ude9b","\ud83d\ude9c","\ud83c\udfce\ufe0f","\ud83c\udfcd\ufe0f","\ud83d\udef5","\ud83e\uddbd","\ud83e\uddbc","\ud83d\udef4","\ud83d\udeb2","\ud83d\udefa","\ud83d\ude81","\ud83d\udef8","\u2708\ufe0f","\ud83d\udeeb","\ud83d\udeec","\ud83e\ude82","\ud83d\udcba","\ud83d\ude80","\ud83d\udea4","\u26f5","\ud83d\udee5\ufe0f","\ud83d\udef3\ufe0f","\u26f4\ufe0f","\ud83d\udea2","\u2693","\u26fd","\ud83d\udea7","\ud83d\udea6","\ud83d\udea5","\ud83d\uddfa\ufe0f","\ud83d\uddff","\ud83d\udec2","\ud83d\udec3","\ud83d\udec4","\ud83d\udec5"],"Food & Drink":["\ud83c\udf4f","\ud83c\udf4e","\ud83c\udf50","\ud83c\udf4a","\ud83c\udf4b","\ud83c\udf4c","\ud83c\udf49","\ud83c\udf47","\ud83c\udf53","\ud83c\udf48","\ud83c\udf52","\ud83c\udf51","\ud83e\udd6d","\ud83c\udf4d","\ud83e\udd65","\ud83e\udd5d","\ud83c\udf45","\ud83c\udf46","\ud83e\udd51","\ud83e\udd66","\ud83e\udd6c","\ud83e\udd52","\ud83c\udf36\ufe0f","\ud83c\udf3d","\ud83e\udd55","\ud83e\udd54","\ud83c\udf60","\ud83e\udd50","\ud83e\udd6f","\ud83c\udf5e","\ud83e\udd56","\ud83e\udd68","\ud83e\uddc0","\ud83e\udd5a","\ud83c\udf73","\ud83e\udd5e","\ud83e\udd53","\ud83e\udd69","\ud83c\udf57","\ud83c\udf56","\ud83e\uddb4","\ud83c\udf2d","\ud83c\udf54","\ud83c\udf5f","\ud83c\udf55","\ud83e\udd6a","\ud83e\udd59","\ud83c\udf2e","\ud83c\udf2f","\ud83e\udd57","\ud83e\udd58","\ud83e\udd6b","\ud83c\udf5d","\ud83c\udf5c","\ud83c\udf72","\ud83c\udf5b","\ud83c\udf63","\ud83c\udf71","\ud83e\udd5f","\ud83e\uddaa","\ud83c\udf64","\ud83c\udf59","\ud83c\udf5a","\ud83c\udf58","\ud83c\udf65","\ud83e\udd60","\ud83e\udd6e","\ud83c\udf62","\ud83c\udf61","\ud83c\udf67","\ud83c\udf68","\ud83c\udf66","\ud83e\udd67","\ud83c\udf70","\ud83c\udf82","\ud83c\udf6e","\ud83c\udf6d","\ud83c\udf6c","\ud83c\udf6b","\ud83c\udf7f","\ud83c\udf69","\ud83c\udf6a","\ud83c\udf30","\ud83e\udd5c","\ud83c\udf6f","\ud83e\udd5b","\ud83c\udf7c","\u2615","\ud83c\udf75","\ud83e\uddc3","\ud83e\udd64","\ud83c\udf76","\ud83c\udf7a","\ud83c\udf7b","\ud83e\udd42","\ud83c\udf77","\ud83e\udd43","\ud83c\udf78","\ud83c\udf79","\ud83e\uddc9","\ud83c\udf7e","\ud83e\uddca"],"Activities & Sports":["\u26bd","\ud83c\udfc0","\
1ud83c\udfc8","\u26be","\ud83e\udd4e","\ud83c\udfbe","\ud83c\udfd0","\ud83c\udfc9","\ud83e\udd4f","\ud83c\udfb1","\ud83c\udfd3","\ud83c\udff8","\ud83e\udd45","\ud83c\udfd2","\ud83c\udfd1","\ud83c\udfcf","\ud83e\udd4d","\ud83c\udff9","\ud83c\udfa3","\ud83e\udd4a","\ud83e\udd4b","\ud83c\udfbd","\ud83d\udef9","\ud83d\udef7","\u26f8\ufe0f","\ud83e\udd4c","\ud83c\udfbf","\u26f7\ufe0f","\ud83c\udfc2","\ud83c\udfcb\ufe0f","\ud83e\udd3c","\ud83e\udd38","\ud83e\udd3a","\u26f9\ufe0f","\ud83e\udd3e","\ud83c\udfcc\ufe0f","\ud83c\udfc7","\ud83e\uddd8","\ud83c\udfc4","\ud83c\udfca","\ud83d\udea3","\ud83e\uddd7","\ud83d\udeb5","\ud83d\udeb4","\ud83c\udfc6","\ud83e\udd47","\ud83e\udd48","\ud83e\udd49","\ud83c\udfc5","\ud83c\udf96\ufe0f","\ud83c\udff5\ufe0f","\ud83c\udf97\ufe0f","\ud83c\udfab","\ud83c\udf9f\ufe0f","\ud83c\udfaa","\ud83e\udd39","\ud83c\udfad","\ud83e\ude70","\ud83c\udfa8","\ud83c\udfac","\ud83c\udfa4","\ud83c\udfa7","\ud83c\udfbc","\ud83c\udfb9","\ud83e\udd41","\ud83c\udfb7","\ud83c\udfba","\ud83c\udfb8","\ud83e\ude95","\ud83c\udfbb","\ud83c\udfb2","\u265f\ufe0f","\ud83c\udfaf","\ud83c\udfb3","\ud83c\udfae","\ud83c\udfb0","\ud83e\udde9"],"Travel & Places":["\ud83d\ude97","\ud83d\ude95","\ud83d\ude99","\ud83d\ude8c","\ud83d\ude8e","\ud83c\udfce\ufe0f","\ud83d\ude93","\ud83d\ude91","\ud83d\ude92","\ud83d\ude90","\ud83d\ude9a","\ud83d\ude9b","\ud83d\ude9c","\ud83d\udef4","\ud83d\udeb2","\ud83d\udef5","\ud83c\udfcd\ufe0f","\ud83d\udea8","\ud83d\ude94","\ud83d\ude8d","\ud83d\ude98","\ud83d\ude96","\ud83d\udea1","\ud83d\udea0","\ud83d\ude9f","\ud83d\ude83","\ud83d\ude8b","\ud83d\ude9e","\ud83d\ude9d","\ud83d\ude84","\ud83d\ude85","\ud83d\ude88","\ud83d\ude82","\ud83d\ude86","\ud83d\ude87","\ud83d\ude8a","\ud83d\ude89","\u2708\ufe0f","\ud83d\udeeb","\ud83d\udeec","\ud83d\udee9\ufe0f","\ud83d\udcba","\ud83d\ude80","\ud83d\ude81","\ud83d\udef8","\ud83d\udea4","\u26f5","\ud83d\udee5\ufe0f","\ud83d\udea2","\u26f4\ufe0f","\ud83d\udef3\ufe0f","\ud83d\ude9b","\ud83d\ude90","\ud83c\udfe0","\ud83c\udfe1","\ud83c\udfd8\ufe0f","\ud83c\udfda\ufe0f","\ud83c\udfd7\ufe0f","\ud83c\udfed","\ud83c\udfe2","\ud83c\udfec","\ud83c\udfe3","\ud83c\udfe4","\ud83c\udfe5","\ud83c\udfe6","\ud83c\udfe8","\ud83c\udfea","\ud83c\udfeb","\ud83c\udfe9","\ud83d\udc92","\ud83c\udfdb\ufe0f","\u26ea","\ud83d\udd4c","\ud83d\udd4d","\ud83d\udd4b","\u26e9\ufe0f","\ud83d\udee4\ufe0f","\ud83d\udee3\ufe0f","\ud83d\uddfe","\ud83c\udf91","\ud83c\udfde\ufe0f","\ud83c\udf05","\ud83c\udf04","\ud83c\udf20","\ud83c\udf87","\ud83c\udf86","\ud83c\udf07","\ud83c\udf06","\ud83c\udfd9\ufe0f","\ud83c\udf03","\ud83c\udf0c","\ud83c\udf09","\ud83c\udf01"],Objects:["\u231a","\ud83d\udcf1","\ud83d\udcf2","\ud83d\udcbb","\u2328\ufe0f","\ud83d\udda5\ufe0f","\ud83d\udda8\ufe0f","\ud83d\uddb1\ufe0f","\ud83d\uddb2\ufe0f","\ud83d\udd79\ufe0f","\ud83d\udddc\ufe0f","\ud83d\udcbe","\ud83d\udcbf","\ud83d\udcc0","\ud83d\udcfc","\ud83d\udcf7","\ud83d\udcf8","\ud83d\udcf9","\ud83c\udfa5","\ud83d\udcfd\ufe0f","\ud83c\udf9e\ufe0f","\ud83d\udcde","\u260e\ufe0f","\ud83d\udcdf","\ud83d\udce0","\ud83d\udcfa","\ud83d\udcfb","\ud83c\udf99\ufe0f","\ud83c\udf9a\ufe0f","\ud83c\udf9b\ufe0f","\u23f1\ufe0f","\u23f2\ufe0f","\u23f0","\ud83d\udd70\ufe0f","\u231b","\u23f3","\ud83d\udce1","\ud83d\udd0b","\ud83d\udd0c","\ud83d\udca1","\ud83d\udd26","\ud83d\udd6f\ufe0f","\ud83e\ude94","\ud83e\uddef","\ud83d\udee2\ufe0f","\ud83d\udcb8","\ud83d\udcb5","\ud83d\udcb4","\ud83d\udcb6","\ud83d\udcb7","\ud83d\udcb0","\ud83d\udcb3","\ud83d\udc8e","\u2696\ufe0f","\ud83e\ude9c","\ud83e\uddf0","\ud83e\ude9b","\ud83d\udd27","\ud83d\udd28","\u2692\ufe0f","\ud83d\udee0\ufe0f","\u26cf\ufe0f","\ud83e\ude9a","\ud83d\udd29","\u2699\ufe0f","\ud83e\udea4","\ud83e\uddf1","\u26d3\ufe0f","\ud83e\uddf2","\ud83d\udd2b","\ud83d\udca3","\ud83e\udde8","\ud83e\ude93","\ud83d\udd2a","\ud83d\udde1\ufe0f","\u2694\ufe0f","\ud83d\udee1\ufe0f","\ud83d\udeac","\u26b0\ufe0f","\ud83e\udea6","\u26b1\ufe0f","\ud83c\udffa","\ud83d\udd2e","\ud83d\udcff","\ud83e\uddff","\ud83d\udc88","\u2697\ufe0f","\ud83d\udd2d","\ud83d\udd2c","\ud83d\udd73\ufe0f","\ud83e\ude79","\ud83e\ude7a","\ud83d\udc8a","\ud83d\udc89","\ud83e\ude78","\ud83e\uddec","\ud83e\udda0","\ud83e\uddeb","\ud83e\uddea","\ud83c\udf21\ufe0f","\ud83e\uddf9","\ud83e\udea0","\ud83e\uddfa","\ud83e\uddfb","\ud83d\udebd","\ud83d\udebf","\ud83d\udec1","\ud83d\udec0","\ud83e\uddfc","\ud83e\udea5","\ud83e\ude92","\ud83e\uddfd","\ud83e\udea3","\ud83e\uddf4","\ud83d\udece\ufe0f","\ud83d\udd11","\ud83d\udddd\ufe0f","\ud83d\udeaa","\ud83e\ude91","\ud83d\udecb\ufe0f","\ud83d\udecf\ufe0f","\ud83d\udecc","\ud83e\uddf8","\ud83e\ude86","\ud83d\uddbc\ufe0f","\ud83e\ude9e","\ud83e\ude9f","\ud83d\udecd\ufe0f","\ud83d\uded2","\ud83c\udf81","\ud83c\udf88","\ud83c\udf8f","\ud83c\udf80","\ud83e\ude84","\ud83e\ude85","\ud83e\udea9","\ud83c\udf8a","\ud83c\udf89","\ud83c\udf8e","\ud83c\udfee","\ud83c\udf90","\ud83e\udde7","\u2709\ufe0f","\ud83d\udce9","\ud83d\udce8","\ud83d\udce7","\ud83d\udc8c","\ud83d\udce5","\ud83d\udce4","\ud83d\udce6","\ud83c\udff7\ufe0f","\ud83e\udea7","\ud83d\udcea","\ud83d\udceb","\ud83d\udcec","\ud83d\udced","\ud83d\udcee","\ud83d\udcef","\ud83d\udcdc","\ud83d\udcc3","\ud83d\udcc4","\ud83d\udcd1","\ud83e\uddfe","\ud83d\udcca","\ud83d\udcc8","\ud83d\udcc9","\ud83d\uddd2\ufe0f","\ud83d\uddd3\ufe0f","\ud83d\udcc6","\ud83d\udcc5","\ud83d\uddd1\ufe0f","\ud83d\udcc7","\ud83d\uddc3\ufe0f","\ud83d\uddf3\ufe0f","\ud83d\uddc4\ufe0f","\ud83d\udccb","\ud83d\udcc1","\ud83d\udcc2","\ud83d\uddc2\ufe0f","\ud83d\uddde\ufe0f","\ud83d\udcf0","\ud83d\udcd3","\ud83d\udcd4","\ud83d\udcd2","\ud83d\udcd5","\ud83d\udcd7","\ud83d\udcd8","\ud83d\udcd9","\ud83d\udcda","\ud83d\udcd6","\ud83d\udd16","\ud83e\uddf7","\ud83d\udd17","\ud83d\udcce","\ud83d\udd87\ufe0f","\ud83d\udcd0","\ud83d\udccf","\ud83e\uddee","\ud83d\udccc","\ud83d\udccd","\u2702\ufe0f","\ud83d\udd8a\ufe0f","\ud83d\udd8b\ufe0f","\u2712\ufe0f","\ud83d\udd8c\ufe0f","\ud83d\udd8d\ufe0f","\ud83d\udcdd","\u270f\ufe0f","\ud83d\udd0d","\ud83d\udd0e","\ud83d\udd0f","\ud83d\udd10","\ud83d\udd12","\ud83d\udd13"],Symbols:["\u2764\ufe0f","\ud83e\udde1","\ud83d\udc9b","\ud83d\udc9a","\ud83d\udc99","\ud83d\udc9c","\ud83d\udda4","\ud83e\udd0d","\ud83e\udd0e","\ud83d\udc94","\u2763\ufe0f","\ud83d\udc95","\ud83d\udc9e","\ud83d\udc93","\ud83d\udc97","\ud83d\udc96","\ud83d\udc98","\ud83d\udc9d","\ud83d\udc9f","\u262e\ufe0f","\u271d\ufe0f","\u262a\ufe0f","\ud83d\udd49\ufe0f","\u2638\ufe0f","\u2721\ufe0f","\ud83d\udd2f","\ud83d\udd4e","\u262f\ufe0f","\u2626\ufe0f","\ud83d\uded0","\u26ce","\u2648","\u2649","\u264a","\u264b","\u264c","\u264d","\u264e","\u264f","\u2650","\u2651","\u2652","\u2653","\ud83c\udd94","\u269b\ufe0f","\ud83c\ude51","\u2622\ufe0f","\u2623\ufe0f","\ud83d\udcf4","\ud83d\udcf3","\ud83c\ude36","\ud83c\ude1a","\ud83c\ude38","\ud83c\ude3a","\ud83c\ude37\ufe0f","\u2734\ufe0f","\ud83c\udd9a","\ud83d\udcae","\ud83c\ude50","\u3299\ufe0f","\u3297\ufe0f","\ud83c\ude34","\ud83c\ude35","\ud83c\ude39","\ud83c\ude32","\ud83c\udd70\ufe0f","\ud83c\udd71\ufe0f","\ud83c\udd8e","\ud83c\udd91","\ud83c\udd7e\ufe0f","\ud83c\udd98","\u274c","\u2b55","\ud83d\uded1","\u26d4","\ud83d\udcdb","\ud83d\udeab","\ud83d\udcaf","\ud83d\udca2","\u2668\ufe0f","\ud83d\udeb7","\ud83d\udeaf","\ud83d\udeb3","\ud83d\udeb1","\ud83d\udd1e","\ud83d\udcf5","\ud83d\udead","\u2757","\u2753","\u2755","\u2754","\u203c\ufe0f","\u2049\ufe0f","\ud83d\udd05","\ud83d\udd06","\u303d\ufe0f","\u26a0\ufe0f","\ud83d\udeb8","\ud83d\udd31","\u269c\ufe
10f","\ud83d\udd30","\u267b\ufe0f","\u2705","\ud83c\ude2f","\ud83d\udcb9","\u2747\ufe0f","\u2733\ufe0f","\u274e","\ud83c\udf10","\ud83d\udca0","\u24c2\ufe0f","\ud83c\udf00","\ud83d\udca4","\ud83c\udfe7","\ud83d\udebe","\u267f","\ud83c\udd7f\ufe0f","\ud83c\ude33","\ud83c\ude02\ufe0f","\ud83d\udec2","\ud83d\udec3","\ud83d\udec4","\ud83d\udec5","\ud83d\udeb9","\ud83d\udeba","\ud83d\udebc","\ud83d\udebb","\ud83d\udeae","\ud83c\udfa6","\ud83d\udcf6","\ud83c\ude01","\ud83d\udd23","\u2139\ufe0f","\ud83d\udd24","\ud83d\udd21","\ud83d\udd20","\ud83d\udd22","\ud83d\udd1f","\ud83d\udd22","\ud83d\udd20","\ud83d\udd21","\ud83d\udd24","\u2139\ufe0f","\ud83d\udd23","\ud83c\ude01","\ud83d\udcf6","\ud83c\udfa6","\ud83d\udeae","\ud83d\udebb","\ud83d\udebc","\ud83d\udeba","\ud83d\udeb9","\ud83d\udec5","\ud83d\udec4","\ud83d\udec3","\ud83d\udec2","\ud83c\ude02\ufe0f","\ud83c\ude33","\ud83c\udd7f\ufe0f","\u267f","\ud83d\udebe","\ud83c\udfe7","\ud83d\udca4","\ud83c\udf00","\u24c2\ufe0f","\ud83d\udca0","\ud83c\udf10","\u274e","\u2733\ufe0f","\u2747\ufe0f","\ud83d\udcb9","\ud83c\ude2f","\u2705","\u267b\ufe0f","\ud83d\udd30","\u269c\ufe0f","\ud83d\udd31","\ud83d\udeb8","\u26a0\ufe0f","\u303d\ufe0f","\ud83d\udd06","\ud83d\udd05","\u2049\ufe0f","\u203c\ufe0f","\u2754","\u2755","\u2753","\u2757","\ud83d\udead","\ud83d\udcf5","\ud83d\udd1e","\ud83d\udeb1","\ud83d\udeb3","\ud83d\udeaf","\ud83d\udeb7","\u2668\ufe0f","\ud83d\udca2","\ud83d\udcaf","\ud83d\udeab","\ud83d\udcdb","\u26d4","\ud83d\uded1","\u2b55","\u274c","\ud83c\udd98","\ud83c\udd7e\ufe0f","\ud83c\udd91","\ud83c\udd8e","\ud83c\udd71\ufe0f","\ud83c\udd70\ufe0f","\ud83c\ude32","\ud83c\ude39","\ud83c\ude35","\ud83c\ude34","\u3297\ufe0f","\u3299\ufe0f","\ud83c\ude50","\ud83d\udcae","\ud83c\udd9a","\u2734\ufe0f","\ud83c\ude37\ufe0f","\ud83c\ude3a","\ud83c\ude38","\ud83c\ude1a","\ud83c\ude36","\ud83d\udcf3","\ud83d\udcf4","\u2623\ufe0f","\u2622\ufe0f","\ud83c\ude51","\u269b\ufe0f","\ud83c\udd94","\u2653","\u2652","\u2651","\u2650","\u264f","\u264e","\u264d","\u264c","\u264b","\u264a","\u2649","\u2648","\u26ce","\ud83d\uded0","\u2626\ufe0f","\u262f\ufe0f","\ud83d\udd4e","\ud83d\udd2f","\u2721\ufe0f","\u2638\ufe0f","\ud83d\udd49\ufe0f","\u262a\ufe0f","\u271d\ufe0f","\u262e\ufe0f","\ud83d\udc9f","\ud83d\udc9d","\ud83d\udc98","\ud83d\udc96","\ud83d\udc97","\ud83d\udc93","\ud83d\udc9e","\ud83d\udc95","\u2763\ufe0f","\ud83d\udc94","\ud83e\udd0e","\ud83e\udd0d","\ud83d\udda4","\ud83d\udc9c","\ud83d\udc99","\ud83d\udc9a","\ud83d\udc9b","\ud83e\udde1","\u2764\ufe0f"],Flags:["\ud83c\udff3\ufe0f","\ud83c\udff4","\ud83c\udfc1","\ud83d\udea9","\ud83c\udff3\ufe0f\u200d\ud83c\udf08","\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f","\ud83c\uddfa\ud83c\uddf3","\ud83c\udde6\ud83c\uddeb","\ud83c\udde6\ud83c\uddfd","\ud83c\udde6\ud83c\uddf1","\ud83c\udde9\ud83c\uddff","\ud83c\udde6\ud83c\uddf8","\ud83c\udde6\ud83c\udde9","\ud83c\udde6\ud83c\uddf4","\ud83c\udde6\ud83c\uddee","\ud83c\udde6\ud83c\uddf6","\ud83c\udde6\ud83c\uddec","\ud83c\udde6\ud83c\uddf7","\ud83c\udde6\ud83c\uddf2","\ud83c\udde6\ud83c\uddfc","\ud83c\udde6\ud83c\uddfa","\ud83c\udde6\ud83c\uddf9","\ud83c\udde6\ud83c\uddff","\ud83c\udde7\ud83c\uddf8","\ud83c\udde7\ud83c\udded","\ud83c\udde7\ud83c\udde9","\ud83c\udde7\ud83c\udde7","\ud83c\udde7\ud83c\uddfe","\ud83c\udde7\ud83c\uddea","\ud83c\udde7\ud83c\uddff","\ud83c\udde7\ud83c\uddef","\ud83c\udde7\ud83c\uddf2","\ud83c\udde7\ud83c\uddf9","\ud83c\udde7\ud83c\uddf4","\ud83c\udde7\ud83c\udde6","\ud83c\udde7\ud83c\uddfc","\ud83c\udde7\ud83c\uddf7","\ud83c\uddee\ud83c\uddf4","\ud83c\uddfb\ud83c\uddec","\ud83c\udde7\ud83c\uddf3","\ud83c\udde7\ud83c\uddec","\ud83c\udde7\ud83c\uddeb","\ud83c\udde7\ud83c\uddee","\ud83c\uddf0\ud83c\udded","\ud83c\udde8\ud83c\uddf2","\ud83c\udde8\ud83c\udde6","\ud83c\uddee\ud83c\uddf6","\ud83c\uddee\ud83c\uddf7","\ud83c\uddee\ud83c\uddea","\ud83c\uddee\ud83c\uddf2","\ud83c\uddee\ud83c\uddf1","\ud83c\uddee\ud83c\uddf9","\ud83c\uddef\ud83c\uddea","\ud83c\uddef\ud83c\uddf2","\ud83c\uddef\ud83c\uddf5","\ud83c\uddef\ud83c\uddf4","\ud83c\uddf0\ud83c\uddff","\ud83c\uddf0\ud83c\uddea","\ud83c\uddf0\ud83c\uddee","\ud83c\uddf0\ud83c\uddfc","\ud83c\uddf0\ud83c\uddec","\ud83c\uddf1\ud83c\udde6","\ud83c\uddf1\ud83c\uddfb","\ud83c\uddf1\ud83c\udde7","\ud83c\uddf1\ud83c\uddf8","\ud83c\uddf1\ud83c\uddf7","\ud83c\uddf1\ud83c\uddfe","\ud83c\uddf1\ud83c\uddee","\ud83c\uddf1\ud83c\uddf9","\ud83c\uddf1\ud83c\uddfa","\ud83c\uddf2\ud83c\uddf4","\ud83c\uddf2\ud83c\uddec","\ud83c\uddf2\ud83c\uddfc","\ud83c\uddf2\ud83c\uddfe","\ud83c\uddf2\ud83c\uddfb","\ud83c\uddf2\ud83c\uddf1","\ud83c\uddf2\ud83c\uddf9","\ud83c\uddf2\ud83c\udded","\ud83c\uddf2\ud83c\uddf6","\ud83c\uddf2\ud83c\uddf7","\ud83c\uddf2\ud83c\uddfa","\ud83c\uddfe\ud83c\uddf9","\ud83c\uddf2\ud83c\uddfd","\ud83c\uddeb\ud83c\uddf2","\ud83c\uddf2\ud83c\udde9","\ud83c\uddf2\ud83c\udde8","\ud83c\uddf2\ud83c\uddf3","\ud83c\uddf2\ud83c\uddea","\ud83c\uddf2\ud83c\uddf8","\ud83c\uddf2\ud83c\udde6","\ud83c\uddf2\ud83c\uddff","\ud83c\uddf2\ud83c\uddf2","\ud83c\uddf3\ud83c\udde6","\ud83c\uddf3\ud83c\uddf7","\ud83c\uddf3\ud83c\uddf5","\ud83c\uddf3\ud83c\uddf1","\ud83c\uddf3\ud83c\udde8","\ud83c\uddf3\ud83c\uddff","\ud83c\uddf3\ud83c\uddee","\ud83c\uddf3\ud83c\uddea","\ud83c\uddf3\ud83c\uddec","\ud83c\uddf3\ud83c\uddfa","\ud83c\uddf3\ud83c\uddeb","\ud83c\uddf0\ud83c\uddf5","\ud83c\uddf2\ud83c\uddf0","\ud83c\uddf2\ud83c\uddf5","\ud83c\uddf3\ud83c\uddf4","\ud83c\uddf4\ud83c\uddf2","\ud83c\uddf5\ud83c\uddf0","\ud83c\uddf5\ud83c\uddfc","\ud83c\uddf5\ud83c\uddf8","\ud83c\uddf5\ud83c\udde6","\ud83c\uddf5\ud83c\uddec","\ud83c\uddf5\ud83c\uddfe","\ud83c\uddf5\ud83c\uddea","\ud83c\uddf5\ud83c\udded","\ud83c\uddf5\ud83c\uddf3","\ud83c\uddf5\ud83c\uddf1","\ud83c\uddf5\ud83c\uddf9","\ud83c\uddf5\ud83c\uddf7","\ud83c\uddf6\ud83c\udde6","\ud83c\uddf7\ud83c\uddea","\ud83c\uddf7\ud83c\uddf4","\ud83c\uddf7\ud83c\uddfa","\ud83c\uddf7\ud83c\uddfc","\ud83c\uddfc\ud83c\uddf8","\ud83c\uddf8\ud83c\uddf2","\ud83c\uddf8\ud83c\udde6","\ud83c\uddf8\ud83c\uddf3","\ud83c\uddf7\ud83c\uddf8","\ud83c\uddf8\ud83c\udde8","\ud83c\uddf8\ud83c\uddf1","\ud83c\uddf8\ud83c\uddec","\ud83c\uddf8\ud83c\uddfd","\ud83c\uddf8\ud83c\uddf0","\ud83c\uddf8\ud83c\uddee","\ud83c\uddec\ud83c\uddf8","\ud83c\uddf8\ud83c\udde7","\ud83c\uddf8\ud83c\uddf4","\ud83c\uddff\ud83c\udde6","\ud83c\uddf0\ud83c\uddf7","\ud83c\uddf8\ud83c\uddf8","\ud83c\uddea\ud83c\uddf8","\ud83c\uddf1\ud83c\uddf0","\ud83c\udde7\ud83c\uddf1","\ud83c\uddf8\ud83c\udded","\ud83c\uddf0\ud83c\uddf3","\ud83c\uddf1\ud83c\udde8","\ud83c\uddf5\ud83c\uddf2","\ud83c\uddfb\ud83c\udde8","\ud83c\uddf8\ud83c\udde9","\ud83c\uddf8\ud83c\uddf7","\ud83c\uddf8\ud83c\uddea","\ud83c\udde8\ud83c\udded","\ud83c\uddf8\ud83c\uddfe","\ud83c\uddf9\ud83c\uddfc","\ud83c\uddf9\ud83c\uddef","\ud83c\uddf9\ud83c\uddff","\ud83c\uddf9\ud83c\udded","\ud83c\uddf9\ud83c\uddf1","\ud83c\uddf9\ud83c\uddec","\ud83c\uddf9\ud83c\uddf0","\ud83c\uddf9\ud83c\uddf4","\ud83c\uddf9\ud83c\uddf9","\ud83c\uddf9\ud83c\uddf3","\ud83c\uddf9\ud83c\uddf7","\ud83c\uddf9\ud83c\uddf2","\ud83c\uddf9\ud83c\udde8","\ud83c\uddf9\ud83c\uddfb","\ud83c\uddfb\ud83c\uddee","\ud83c\uddfa\ud83c\uddec","\ud83c\uddfa\ud83c\udde6","\ud83c\udde6\ud83c\uddea","\ud83c\uddec\ud83c\udde7","\ud83c\uddfa\ud83c\uddf8","\ud83c\uddfa\ud83c\uddfe","\ud83c\uddfa\ud83c\uddff","\ud83c\uddfb\ud83c\uddfa","\ud83c\uddfb\ud83c\udde6","\ud83c\uddfb\ud83c\uddea","\ud83c\uddfb\ud83c\uddf3","\ud83c\uddfc\ud83c\uddeb","\ud83c\uddea\ud83c\udded","\ud83c\uddfe\ud83c\uddea","\ud83c\uddff\ud83c\uddf2","\ud83c\uddff\ud83c\uddfc"]},Ht={smile:["\ud83d\ude00","\ud83d\ude03","\ud83d\ude04","\ud83d\ude01","\ud83d\ude06","\ud83d\ude05","\ud83e\udd23","\ud83d\ude02","\ud83d\ude42","\ud83d\ude43","\ud83d\ude09","\ud83d\ude0a","\ud83d\ude07","\ud83e\udd70","\ud83d\ude0d"],happy:["\ud83d\ude00","\ud83d\ude03","\ud83d\ude04","\ud83d\ude01","\ud83d\ude06","\ud83d\ude05","\ud83e\udd23","\ud83d\ude02","\ud83d\ude42","\ud83d\ude43","\ud83d\ude09","\ud83d\ude0a","\ud83d\ude07","\ud83e\udd70","\ud83d\ude0d","\ud83e\udd29","\ud83d\ude18","\ud83d\ude17","\ud83d\ude1a","\ud83d\ude19","\ud83d\ude0b","\ud83d\ude1b","\ud83d\ude1c","\ud83e\udd2a","\ud83d\ude1d","\ud83e\udd11","\ud83e\udd17"],sad:["\ud83d\ude15","\ud83d\ude1f","\ud83d\ude41","\u2639\ufe0f","\ud83d\ude2e","\ud83d\ude2f","\ud83d\ude32","\ud83d\ude33","\ud83e\udd7a","\ud83d\ude26","\ud83d\ude27","\ud83d\ude28","\ud83d\ude30","\ud83d\ude25","\ud83d\ude22","\ud83d\ude2d","\ud83d\ude31","\ud83d\ude16","\ud83d\ude23","\ud83d\ude1e","\ud83d\ude13","\ud83d\ude29","\ud83d\ude2b"],love:["\u2764\ufe0f","\ud83e\udde1","\ud83d\udc9b","\ud83d\udc9a","\ud83d\udc99","\ud83d\udc9c","\ud83d\udda4","\ud83e\udd0d","\ud83e\udd0e","\ud83d\udc94","\u2763\ufe0f","\ud83d\udc95","\ud83d\udc9e","\ud83d\udc93","\ud83d\udc97","\ud83d\udc96","\ud83d\udc98","\ud83d\udc9d","\ud83d\udc9f","\ud83e\udd70","\ud83d\ude0d","\ud83d\ude18","\ud83d\ude17","\ud83d\ude1a","\ud83d\ude19"],work:["\ud83d\udcbc","\ud83d\udc54","\ud83d\udc68\u200d\ud83d\udcbc","\ud83d\udc69\u200d\ud83d\udcbc","\ud83d\udcbb","\ud83d\udcca","\ud83d\udcc8","\ud83d\udcc9","\ud83d\udccb","\ud83d\udcc1","\ud83d\udcc2","\ud83d\uddc2\ufe0f","\ud83d\udcdd","\u270f\ufe0f","\ud83d\udd8a\ufe0f","\ud83d\udd8b\ufe0f","\u2712\ufe0f","\ud83d\udd8c\ufe0f","\ud83d\udd8d\ufe0f"],money:["\ud83d\udcb0","\ud83d\udcb5","\ud83d\udcb4","\ud83d\udcb6","\ud83d\udcb7","\ud83d\udcb8","\ud83d\udcb3","\ud83d\udc8e","\ud83e\udd11"],food:["\ud83c\udf4f","\ud83c\udf4e","\ud83c\udf50","\ud83c\udf4a","\ud83c\udf4b","\ud83c\udf4c","\ud83c\udf49","\ud83c\udf47","\ud83c\udf53","\ud83c\udf48","\ud83c\udf52","\ud83c\udf51","\ud83e\udd6d","\ud83c\udf4d","\ud83e\udd65","\ud83e\udd5d","\ud83c\udf45","\ud83c\udf46","\ud83e\udd51","\ud83e\udd66","\ud83e\udd6c","\ud83e\udd52","\ud83c\udf36\ufe0f","\ud83c\udf3d","\ud83e\udd55","\ud83e\udd54","\ud83c\udf60","\ud83e\udd50","\ud83e\udd6f","\ud83c\udf5e","\ud83e\udd56","\ud83e\udd68","\ud83e\uddc0","\ud83e\udd5a","\ud83c\udf73","\ud83e\udd5e","\ud83e\udd53","\ud83e\udd69","\ud83c\udf57","\ud83c\udf56","\ud83e\uddb4","\ud83c\udf2d","\ud83c\udf54","\ud83c\udf5f","\ud83c\udf55","\ud83e\udd6a","\ud83e\udd59","\ud83c\udf2e","\ud83c\udf2f","\ud83e\udd57","\ud83e\udd58","\ud83e\udd6b","\ud83c\udf5d","\ud83c\udf5c","\ud83c\udf72","\ud83c\udf5b","\ud83c\udf63","\ud83c\udf71","\ud83e\udd5f","\ud83e\uddaa","\ud83c\udf64","\ud83c\udf59","\ud83c\udf5a","\ud83c\udf58","\ud83c\udf65","\ud83e\udd60","\ud83e\udd6e","\ud83c\udf62","\ud83c\udf61","\ud83c\udf67","\ud83c\udf68","\ud83c\udf66","\ud83e\udd67","\ud83c\udf70","\ud83c\udf82","\ud83c\udf6e","\ud83c\udf6d","\ud83c\udf6c","\ud83c\udf6b","\ud83c\udf7f","\ud83c\udf69","\ud83c\udf6a","\ud83c\udf30","\ud83e\udd5c","\ud83c\udf6f","\ud83e\udd5b","\ud83c\udf7c","\u2615","\ud83c\udf75","\ud83e\uddc3","\ud83e\udd64","\ud83c\udf76","\ud83c\udf7a","\ud83c\udf7b","\ud83e\udd42","\ud83c\udf77","\ud83e\udd43","\ud83c\udf78","\ud83c\udf79","\ud83e\uddc9","\ud83c\udf7e","\ud83e\uddca"],travel:["\u2708\ufe0f","\ud83d\udeeb","\ud83d\udeec","\ud83d\udee9\ufe0f","\ud83d\udcba","\ud83d\ude80","\ud83d\ude81","\ud83d\udef8","\ud83d\udea4","\u26f5","\ud83d\udee5\ufe0f","\ud83d\udea2","\u26f4\ufe0f","\ud83d\udef3\ufe0f","\ud83d\ude97","\ud83d\ude95","\ud83d\ude99","\ud83d\ude8c","\ud83d\ude8e","\ud83c\udfce\ufe0f","\ud83d\ude93","\ud83d\ude91","\ud83d\ude92","\ud83d\ude90","\ud83d\ude9a","\ud83d\ude9b","\ud83d\ude9c","\ud83d\udef4","\ud83d\udeb2","\ud83d\udef5","\ud83c\udfcd\ufe0f"],sport:["\u26bd","\ud83c\udfc0","\ud83c\udfc8","\u26be","\ud83e\udd4e","\ud83c\udfbe","\ud83c\udfd0","\ud83c\udfc9","\ud83e\udd4f","\ud83c\udfb1","\ud83c\udfd3","\ud83c\udff8","\ud83e\udd45","\ud83c\udfd2","\ud83c\udfd1","\ud83c\udfcf","\ud83e\udd4d","\ud83c\udff9","\ud83c\udfa3","\ud83e\udd4a","\ud83e\udd4b","\ud83c\udfbd","\ud83d\udef9","\ud83d\udef7","\u26f8\ufe0f","\ud83e\udd4c","\ud83c\udfbf","\u26f7\ufe0f","\ud83c\udfc2","\ud83c\udfcb\ufe0f","\ud83e\udd3c","\ud83e\udd38","\ud83e\udd3a","\u26f9\ufe0f","\ud83e\udd3e","\ud83c\udfcc\ufe0f","\ud83c\udfc7","\ud83e\uddd8","\ud83c\udfc4","\ud83c\udfca","\ud83d\udea3","\ud83e\uddd7","\ud83d\udeb5","\ud83d\udeb4"],animal:["\ud83d\udc36","\ud83d\udc31","\ud83d\udc2d","\ud83d\udc39","\ud83d\udc30","\ud83e\udd8a","\ud83d\udc3b","\ud83d\udc3c","\ud83d\udc28","\ud83d\udc2f","\ud83e\udd81","\ud83d\udc2e","\ud83d\udc37","\ud83d\udc3d","\ud83d\udc38","\ud83d\udc35","\ud83d\ude48","\ud83d\ude49","\ud83d\ude4a","\ud83d\udc12","\ud83d\udc14","\ud83d\udc27","\ud83d\udc26","\ud83d\udc24","\ud83d\udc23","\ud83d\udc25","\ud83e\udd86","\ud83e\udd85","\ud83e\udd89","\ud83e\udd87","\ud83d\udc3a","\ud83d\udc17","\ud83d\udc34","\ud83e\udd84","\ud83d\udc1d","\ud83d\udc1b","\ud83e\udd8b","\ud83d\udc0c","\ud83d\udc1e","\ud83d\udc1c","\ud83e\udd9f","\ud83e\udd97","\ud83d\udd77\ufe0f","\ud83d\udd78\ufe0f","\ud83e\udd82","\ud83d\udc22","\ud83d\udc0d","\ud83e\udd8e","\ud83e\udd96","\ud83e\udd95","\ud83d\udc19","\ud83e\udd91","\ud83e\udd90","\ud83e\udd9e","\ud83e\udd80","\ud83d\udc21","\ud83d\udc20","\ud83d\udc1f","\ud83d\udc2c","\ud83d\udc33","\ud83d\udc0b","\ud83e\udd88","\ud83d\udc0a","\ud83d\udc05","\ud83d\udc06","\ud83e\udd93","\ud83e\udd8d","\ud83e\udda7","\ud83d\udc18","\ud83e\udd9b","\ud83e\udd8f","\ud83d\udc2a","\ud83d\udc2b","\ud83e\udd92","\ud83e\udd98","\ud83e\udda1","\ud83d\udc03","\ud83d\udc02","\ud83d\udc04","\ud83d\udc0e","\ud83d\udc16","\ud83d\udc0f","\ud83d\udc11","\ud83e\udd99","\ud83d\udc10","\ud83e\udd8c","\ud83d\udc15","\ud83d\udc29","\ud83d\udc08","\ud83d\udc13","\ud83e\udd83","\ud83e\udd9a","\ud83e\udd9c","\ud83e\udda2","\ud83e\udda9","\ud83d\udd4a\ufe0f","\ud83d\udc07","\ud83e\udd9d","\ud83e\udda8","\ud83e\udda6","\ud83e\udda5","\ud83d\udc01","\ud83d\udc00","\ud83d\udc3f\ufe0f","\ud83e\udd94"],music:["\ud83c\udfb5","\ud83c\udfb6","\ud83c\udfa4","\ud83c\udfa7","\ud83c\udfbc","\ud83c\udfb9","\ud83e\udd41","\ud83c\udfb7","\ud83c\udfba","\ud83c\udfb8","\ud83e\ude95","\ud83c\udfbb"],tech:["\ud83d\udcbb","\u2328\ufe0f","\ud83d\udda5\ufe0f","\ud83d\udda8\ufe0f","\ud83d\uddb1\ufe0f","\ud83d\uddb2\ufe0f","\ud83d\udd79\ufe0f","\ud83d\udddc\ufe0f","\ud83d\udcbe","\ud83d\udcbf","\ud83d\udcc0","\ud83d\udcfc","\ud83d\udcf7","\ud83d\udcf8","\ud83d\udcf9","\ud83c\udfa5","\ud83d\udcfd\ufe0f","\ud83c\udf9e\ufe0f","\ud83d\udcde","\u260e\ufe0f","\ud83d\udcdf","\ud83d\udce0","\ud83d\udcfa","\ud83d\udcfb","\ud83c\udf99\ufe0f","\ud83c\udf9a\ufe0f","\ud83c\udf9b\ufe0f","\u231a","\ud83d\udcf1","\ud83d\udcf2"],nature:["\ud83c\udf32","\ud83c\udf33","\ud83c\udf34","\ud83c\udf35","\ud83c\udf36\ufe0f","\ud83c\udf3e","\ud83c\udf3f","\u2618\ufe0f","\ud83c\udf40","\ud83c\udf41","\ud83c\udf42","\ud83c\udf43","\ud83c\udf3a","\ud83c\udf3b","\ud83c\udf39","\ud83c\udf37","\ud83c\udf3c","\ud83c\udf38","\ud83c\udf3e","\ud83c\udf31","\ud83c\udf3f","\ud83c\udf43","\ud83c\udf42","\ud83c\udf41","\ud83c\udf44","\ud83c\udf30","\ud83c\udf0d","\ud83c\udf0e","\ud83c\udf0f","\ud83c\udf10","\ud83d\uddfe","\ud83e\udded","\ud83c\udfd4\ufe0f","\u26f0\ufe0f","\ud83c\udf0b","\ud83d\uddfb","\ud83c\udfd5\ufe0f","\ud83c\udfd6\ufe0f","\ud83c\udfdc\ufe0f","\ud83c\udfdd\ufe0f","\ud83c\udfde\ufe0f","\ud83c\udfdf\ufe0f"],heart:["\u2764\ufe0f","\ud83e\udde1","\ud83d\udc9b","\ud83d\udc9a","\ud83d\udc99","\ud83d\udc9c","\ud83d\udda4","\ud83e\udd0d","\ud83e\udd0e","\ud83d\udc94","\u2763\ufe0f","\ud83d\udc95","\ud83d\udc9e","\ud83d\udc93","\ud83d\udc97","\ud83d\udc96","\ud83d\udc98","\ud83d\udc9d","\ud83d\udc9f"],star:["\u2b50","\ud83c\udf1f","\ud83d\udcab","\u2728"],fire:["\ud83d\udd25","\ud83d\udca5","\u26a1"],thumbs:["\ud83d\udc4d","\ud83d\udc4e"],ok:["\ud83d\udc4c","\u270c\ufe0f","\ud83e\udd1e","\ud83e\udd1f","\ud83e\udd18","\ud83e\udd19"],party:["\ud83c\udf89","\ud83c\udf8a","\ud83c\udf88","\ud83c\udf81","\ud83c\udf82","\ud83c\udf70","\ud83e\udd73","\ud83c\udf86","\ud83c\udf87"],book:["\ud83d\udcda","\ud83d\udcd6","\ud83d\udcd5","\ud83d\udcd7","\ud83d\udcd8","\ud83d\udcd9","\ud83d\udcd3","\ud83d\udcd4","\ud83d\udcd2","\ud83d\udcc3","\ud83d\udcc4","\ud83d\udcd1","\ud83e\uddfe","\ud83d\udcca","\ud83d\udcc8","\ud83d\udcc9","\ud83d\uddd2\ufe0f","\ud83d\uddd3\ufe0f","\ud83d\udcc6","\ud83d\udcc5","\ud83d\udcc7","\ud83d\uddc3\ufe0f","\ud83d\uddf3\ufe0f","\ud83d\uddc4\ufe0f","\ud83d\udccb","\ud83d\udcc1","\ud83d\udcc2","\ud83d\uddc2\ufe0f"],time:["\u23f0","\ud83d\udd70\ufe0f","\u231b","\u23f3","\u23f1\ufe0f","\u23f2\ufe0f","\ud83d\udd50","\ud83d\udd51","\ud83d\
1udd52","\ud83d\udd53","\ud83d\udd54","\ud83d\udd55","\ud83d\udd56","\ud83d\udd57","\ud83d\udd58","\ud83d\udd59","\ud83d\udd5a","\ud83d\udd5b"],weather:["\u2600\ufe0f","\ud83c\udf24\ufe0f","\u26c5","\ud83c\udf25\ufe0f","\u2601\ufe0f","\ud83c\udf26\ufe0f","\ud83c\udf27\ufe0f","\u26c8\ufe0f","\ud83c\udf29\ufe0f","\u26a1","\u2614","\u2744\ufe0f","\ud83c\udf28\ufe0f","\u26c4","\u2603\ufe0f","\ud83c\udf2c\ufe0f","\ud83d\udca8","\ud83d\udca7","\ud83d\udca6","\u2602\ufe0f","\u2614","\ud83c\udf0a","\ud83c\udf2b\ufe0f"],flag:["\ud83c\udff3\ufe0f","\ud83c\udff4","\ud83c\udfc1","\ud83d\udea9","\ud83c\udff3\ufe0f\u200d\ud83c\udf08","\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f","\ud83c\uddfa\ud83c\uddf3"]},Gt=new Map;Object.entries(Ht).forEach(e=>{let t=(0,a.A)(e,2),n=t[0];t[1].forEach(e=>{Gt.has(e)||Gt.set(e,[]),Gt.get(e).push(n)})});const Kt={"\ud83c\udf4f":["apple","green apple"],"\ud83c\udf4e":["apple","red apple"],"\ud83c\udf50":["pear"],"\ud83c\udf4a":["orange","tangerine","mandarin"],"\ud83c\udf4b":["lemon"],"\ud83c\udf4c":["banana"],"\ud83c\udf49":["watermelon"],"\ud83c\udf47":["grapes","grape"],"\ud83c\udf53":["strawberry"],"\ud83c\udf48":["melon","cantaloupe"],"\ud83c\udf52":["cherry","cherries"],"\ud83c\udf51":["peach"],"\ud83e\udd6d":["mango"],"\ud83c\udf4d":["pineapple"],"\ud83e\udd65":["coconut"],"\ud83e\udd5d":["kiwi","kiwifruit"],"\ud83c\udf45":["tomato"],"\ud83c\udf46":["eggplant","aubergine"],"\ud83e\udd51":["avocado"],"\ud83e\udd66":["broccoli"],"\ud83e\udd6c":["leafy greens","lettuce"],"\ud83e\udd52":["cucumber"],"\ud83c\udf36\ufe0f":["pepper","chili","hot pepper"],"\ud83c\udf3d":["corn","ear of corn"],"\ud83e\udd55":["carrot"],"\ud83e\udd54":["potato"],"\ud83c\udf60":["sweet potato","yam"],"\ud83e\udd50":["croissant"],"\ud83e\udd6f":["bagel"],"\ud83c\udf5e":["bread","loaf"],"\ud83e\udd56":["baguette","french bread"],"\ud83e\udd68":["pretzel"],"\ud83e\uddc0":["cheese"],"\ud83e\udd5a":["egg"],"\ud83c\udf73":["cooking","fried egg","pan"],"\ud83e\udd5e":["pancakes","pancake"],"\ud83e\udd53":["bacon"],"\ud83e\udd69":["meat","steak"],"\ud83c\udf57":["chicken leg","drumstick"],"\ud83c\udf56":["meat on bone"],"\ud83c\udf2d":["hot dog"],"\ud83c\udf54":["hamburger","burger"],"\ud83c\udf5f":["fries","french fries"],"\ud83c\udf55":["pizza"],"\ud83e\udd6a":["sandwich"],"\ud83e\udd59":["stuffed flatbread"],"\ud83c\udf2e":["taco"],"\ud83c\udf2f":["burrito"],"\ud83e\udd57":["salad","green salad"],"\ud83e\udd58":["shallow pan of food","paella"],"\ud83e\udd6b":["canned food"],"\ud83c\udf5d":["spaghetti"],"\ud83c\udf5c":["steaming bowl","ramen","noodles"],"\ud83c\udf72":["pot of food","stew"],"\ud83c\udf5b":["curry","curry rice"],"\ud83c\udf63":["sushi"],"\ud83c\udf71":["bento box"],"\ud83e\udd5f":["dumpling"],"\ud83e\uddaa":["oyster"],"\ud83c\udf64":["fried shrimp"],"\ud83c\udf59":["rice ball"],"\ud83c\udf5a":["cooked rice"],"\ud83c\udf58":["rice cracker"],"\ud83c\udf65":["fish cake"],"\ud83e\udd60":["fortune cookie"],"\ud83e\udd6e":["moon cake"],"\ud83c\udf62":["oden"],"\ud83c\udf61":["dango"],"\ud83c\udf67":["shaved ice"],"\ud83c\udf68":["ice cream"],"\ud83c\udf66":["soft ice cream","ice cream cone"],"\ud83e\udd67":["pie"],"\ud83c\udf70":["cake","shortcake"],"\ud83c\udf82":["birthday cake"],"\ud83c\udf6e":["custard","flan","pudding"],"\ud83c\udf6d":["lollipop"],"\ud83c\udf6c":["candy"],"\ud83c\udf6b":["chocolate bar"],"\ud83c\udf7f":["popcorn"],"\ud83c\udf69":["doughnut","donut"],"\ud83c\udf6a":["cookie"],"\ud83c\udf30":["chestnut"],"\ud83e\udd5c":["peanuts","peanut"],"\ud83c\udf6f":["honey pot"],"\ud83e\udd5b":["glass of milk","milk"],"\ud83c\udf7c":["baby bottle"],"\u2615":["coffee","hot beverage"],"\ud83c\udf75":["tea","teacup"],"\ud83e\uddc3":["beverage box"],"\ud83e\udd64":["cup with straw"],"\ud83c\udf76":["sake"],"\ud83c\udf7a":["beer"],"\ud83c\udf7b":["clinking beer mugs","cheers"],"\ud83e\udd42":["clinking glasses","champagne"],"\ud83c\udf77":["wine glass"],"\ud83e\udd43":["tumbler glass","whiskey"],"\ud83c\udf78":["cocktail glass"],"\ud83c\udf79":["tropical drink"],"\ud83e\uddc9":["mate"],"\ud83c\udf7e":["champagne bottle"],"\ud83e\uddca":["ice"],"\ud83d\udc36":["dog","puppy"],"\ud83d\udc31":["cat","kitten"],"\ud83d\udc2d":["mouse"],"\ud83d\udc39":["hamster"],"\ud83d\udc30":["rabbit","bunny"],"\ud83e\udd8a":["fox"],"\ud83d\udc3b":["bear"],"\ud83d\udc3c":["panda"],"\ud83d\udc28":["koala"],"\ud83d\udc2f":["tiger"],"\ud83e\udd81":["lion"],"\ud83d\udc2e":["cow"],"\ud83d\udc37":["pig"],"\ud83d\udc3d":["pig nose"],"\ud83d\udc38":["frog"],"\ud83d\udc35":["monkey"],"\ud83d\udc14":["chicken"],"\ud83d\udc27":["penguin"],"\ud83d\udc26":["bird"],"\ud83d\udc24":["baby chick"],"\ud83e\udd86":["duck"],"\ud83e\udd85":["eagle"],"\ud83e\udd89":["owl"],"\ud83e\udd87":["bat"],"\ud83d\udc3a":["wolf"],"\ud83d\udc17":["boar"],"\ud83d\udc34":["horse"],"\ud83e\udd84":["unicorn"],"\ud83d\udc1d":["bee","honeybee"],"\ud83d\udc1b":["bug"],"\ud83e\udd8b":["butterfly"],"\ud83d\udc0c":["snail"],"\ud83d\udc1e":["ladybug","lady beetle"],"\ud83d\udc1c":["ant"],"\ud83e\udd9f":["mosquito"],"\ud83e\udd97":["cricket"],"\ud83d\udd77\ufe0f":["spider"],"\ud83d\udd78\ufe0f":["spider web"],"\ud83e\udd82":["scorpion"],"\ud83d\udc22":["turtle"],"\ud83d\udc0d":["snake"],"\ud83e\udd8e":["lizard"],"\ud83e\udd96":["t-rex","tyrannosaurus"],"\ud83e\udd95":["sauropod"],"\ud83d\udc19":["octopus"],"\ud83e\udd91":["squid"],"\ud83e\udd90":["shrimp"],"\ud83e\udd9e":["lobster"],"\ud83e\udd80":["crab"],"\ud83d\udc21":["blowfish"],"\ud83d\udc20":["tropical fish"],"\ud83d\udc1f":["fish"],"\ud83d\udc2c":["dolphin"],"\ud83d\udc33":["whale"],"\ud83d\udc0b":["whale"],"\ud83e\udd88":["shark"],"\ud83d\udc0a":["crocodile"],"\ud83d\udc05":["tiger"],"\ud83d\udc06":["leopard"],"\ud83e\udd93":["zebra"],"\ud83e\udd8d":["gorilla"],"\ud83e\udda7":["orangutan"],"\ud83d\udc18":["elephant"],"\ud83e\udd9b":["hippopotamus"],"\ud83e\udd8f":["rhinoceros"],"\ud83d\udc2a":["camel"],"\ud83d\udc2b":["two-hump camel"],"\ud83e\udd92":["giraffe"],"\ud83e\udd98":["kangaroo"],"\ud83e\udda1":["badger"],"\ud83d\udc03":["water buffalo"],"\ud83d\udc02":["ox"],"\ud83d\udc04":["cow"],"\ud83d\udc0e":["horse"],"\ud83d\udc16":["pig"],"\ud83d\udc0f":["ram"],"\ud83d\udc11":["sheep","ewe"],"\ud83e\udd99":["llama"],"\ud83d\udc10":["goat"],"\ud83e\udd8c":["deer"],"\ud83d\udc15":["dog"],"\ud83d\udc29":["poodle"],"\ud83d\udc08"
1:["cat"],"\ud83d\udc13":["rooster"],"\ud83e\udd83":["turkey"],"\ud83e\udd9a":["peacock"],"\ud83e\udd9c":["parrot"],"\ud83e\udda2":["swan"],"\ud83e\udda9":["flamingo"],"\ud83d\udd4a\ufe0f":["dove","peace"],"\ud83d\udc07":["rabbit"],"\ud83e\udd9d":["raccoon"],"\ud83e\udda8":["skunk"],"\ud83e\udda6":["otter"],"\ud83e\udda5":["sloth"],"\ud83d\udc01":["mouse"],"\ud83d\udc00":["rat"],"\ud83d\udc3f\ufe0f":["chipmunk"],"\ud83e\udd94":["hedgehog"],"\ud83c\udf32":["evergreen tree","tree"],"\ud83c\udf33":["deciduous tree","tree"],"\ud83c\udf34":["palm tree"],"\ud83c\udf35":["cactus"],"\ud83c\udf3e":["sheaf of rice","rice"],"\ud83c\udf3f":["herb"],"\u2618\ufe0f":["shamrock"],"\ud83c\udf40":["four leaf clover","clover"],"\ud83c\udf41":["maple leaf"],"\ud83c\udf42":["fallen leaf","autumn leaf"],"\ud83c\udf43":["leaf fluttering in wind","leaf"],"\ud83c\udf3a":["hibiscus"],"\ud83c\udf3b":["sunflower"],"\ud83c\udf39":["rose"],"\ud83c\udf37":["tulip"],"\ud83c\udf3c":["daisy"],"\ud83c\udf38":["cherry blossom"],"\ud83c\udf31":["seedling"],"\ud83c\udf44":["mushroom"],"\ud83c\udf0d":["globe showing europe-africa","earth","world"],"\ud83c\udf0e":["globe showing americas","earth","world"],"\ud83c\udf0f":["globe showing asia-australia","earth","world"],"\ud83d\uddfe":["map of japan"],"\ud83e\udded":["compass"],"\ud83c\udfd4\ufe0f":["snow-capped mountain","mountain"],"\u26f0\ufe0f":["mountain"],"\ud83c\udf0b":["volcano"],"\ud83d\uddfb":["mount fuji"],"\ud83c\udfd5\ufe0f":["camping"],"\ud83c\udfd6\ufe0f":["beach with umbrella"],"\ud83c\udfdc\ufe0f":["desert"],"\ud83c\udfdd\ufe0f":["desert island"],"\ud83c\udfde\ufe0f":["national park"],"\ud83c\udfdf\ufe0f":["stadium"],"\ud83d\ude00":["grinning face","grinning","smile","happy"],"\ud83d\ude03":["grinning face with big eyes","grinning","smile","happy"],"\ud83d\ude04":["grinning face with smiling eyes","grinning","smile","happy"],"\ud83d\ude01":["beaming face with smiling eyes","grinning","smile","happy"],"\ud83d\ude06":["grinning squinting face","grinning","smile","happy"],"\ud83d\ude05":["grinning face with sweat","grinning","smile","happy"],"\ud83e\udd23":["rolling on the floor laughing","laughing","lol","rofl"],"\ud83d\ude02":["face with tears of joy","laughing","tears"],"\ud83d\ude42":["slightly smiling face","smile","happy"],"\ud83d\ude43":["upside-down face","upside down"],"\ud83d\ude09":["winking face","wink"],"\ud83d\ude0a":["smiling face with smiling eyes","smile","happy"],"\ud83d\ude07":["smiling face with halo","angel","innocent"],"\ud83e\udd70":["smiling face with hearts","love","hearts"],"\ud83d\ude0d":["smiling face with heart-eyes","love","hearts"],"\ud83e\udd29":["star-struck","star","eyes"],"\ud83d\ude18":["face blowing a kiss","kiss","love"],"\ud83d\ude17":["kissing face","kiss"],"\ud83d\ude1a":["kissing face with closed eyes","kiss"],"\ud83d\ude19":["kissing face with smiling eyes","kiss"],"\ud83d\ude0b":["face savoring food","yum","delicious"],"\ud83d\ude1b":["face with tongue","tongue"],"\ud83d\ude1c":["winking face with tongue","wink","tongue"],"\ud83e\udd2a":["zany face","crazy"],"\ud83d\ude1d":["squinting face with tongue","tongue"],"\ud83e\udd11":["money-mouth face","money","rich"],"\ud83e\udd17":["hugging face","hug"],"\ud83e\udd2d":["face with hand over mouth","shush","quiet"],"\ud83e\udd2b":["shushing face","shush","quiet"],"\ud83e\udd14":["thinking face","think","thinking"],"\ud83e\udd10":["zipper-mouth face","zipper","quiet"],"\ud83e\udd28":["face with raised eyebrow","suspicious"],"\ud83d\ude10":["neutral face","neutral"],"\ud83d\ude11":["expressionless face","expressionless"],"\ud83d\ude36":["face without mouth","no mouth"],"\ud83d\ude0f":["smirking face","smirk"],"\ud83d\ude12":["unamused face","unamused"],"\ud83d\ude44":["face with rolling eyes","rolling eyes","eyeroll"],"\ud83d\ude2c":["grimacing face","grimace"],"\ud83e\udd25":["lying face","lie","liar"],"\ud83d\ude0c":["relieved face","relieved"],"\ud83d\ude14":["pensive face","pensive","sad"],"\ud83d\ude2a":["sleepy face","sleepy","tired"],"\ud83e\udd24":["drooling face","drool"],"\ud83d\ude34":["sleeping face","sleep","sleeping"],"\ud83d\ude37":["face with medical mask","mask","sick"],"\ud83e\udd12":["face with thermometer","sick","thermometer"],"\ud83e\udd15":["face with head-bandage","hurt","bandage"],"\ud83e\udd22":["nauseated face","sick","nauseated"],"\ud83e\udd2e":["face vomiting","vomit","sick"],"\ud83e\udd27":["sneezing face","sneeze","sick"],"\ud83e\udd75":["hot face","hot","sweat"],"\ud83e\udd76":["cold face","cold","freeze"],"\ud83d\ude36\u200d\ud83c\udf2b\ufe0f":["face in clouds","clouds"],"\ud83d\ude35":["dizzy face","dizzy"],"\ud83d\ude35\u200d\ud83d\udcab":["face with spiral eyes","dizzy","spiral"],"\ud83e\udd2f":["exploding head","mind blown","explosion"],"\ud83e\udd20":["cowboy hat face","cowboy","hat"],"\ud83e\udd73":["partying face","party","celebration"],"\ud83d\ude0e":["smiling face with sunglasses","cool","sunglasses"],"\ud83e\udd13":["nerd face","nerd","glasses"],"\ud83e\uddd0":["face with monocle","monocle","investigating"],"\ud83d\ude15":["confused face","confused"],"\ud83d\ude1f":["worried face","worried"],"\ud83d\ude41":["slightly frowning face","frown","sad"],"\u2639\ufe0f":["frowning face","frown","sad"],"\ud83d\ude2e":["face with open mouth","surprised","open mouth"],"\ud83d\ude2f":["hushed face","hushed","surprised"],"\ud83d\ude32":["astonished face","astonished","surprised"],"\ud83d\ude33":["flushed face","flushed","embarrassed"],"\ud83e\udd7a":["pleading face","pleading","sad"],"\ud83d\ude26":["frowning face with open mouth","frown","sad"],"\ud83d\ude27":["anguished face","anguished","sad"],"\ud83d\ude28":["fearful face","fear","scared"],"\ud83d\ude30":["anxious face with sweat","anxious","sweat"],"\ud83d\ude25":["sad but relieved face","sad","relieved"],"\ud83d\ude22":["crying face","cry","tears","sad"],"\ud83d\ude2d":["loudly crying face","cry","tears","sad"],"\ud83d\ude31":["face screaming in fear","scream","fear"],"\ud83d\ude16":["confounded face","confounded"],"\ud83d\ude23":["persevering face","persevering"],"\ud83d\ude1e":["disappointed face","disappointed","sad"],"\ud83d\ude13":["downcast face with sweat","sweat","sad"],"\ud83d\ude29":["weary face","weary","tired"],"\ud83d\ude2b":["tired face","tired"],"\ud83e\udd71":["yawning face","yawn","tired"],"\ud83d\ude24":["face with steam from nose","steam","angry"],"\ud83d\ude21":["pouting face","pout","angry"],"\ud83d\ude20":["angry face","angry"],"\ud83e\udd2c":["face with symbols on mouth","swearing","cursing"],"\ud83d\ude08":["smiling face with horns","devil","evil"],"\ud83d\udc7f":["angry face with horns","devil","evil","angry"],"\ud83d\udc80":["skull","death","dead"],"\u2620\ufe0f":["skull and crossbones","skull","death","pirate"],"\ud83d\udca9":["pile of poo","poo","poop"],"\ud83e\udd21":["clown face","clown"],"\ud83d\udc79":["ogre","monster"],"\ud83d\udc7a":["goblin","monster"],"\ud83d\udc7b":["ghost","spooky"],"\ud83d\udc7d":["alien","ufo","extraterrestrial"],"\ud83d\udc7e":["alien monster","alien","game"],"\ud83e\udd16":["robot","bot"],"\ud83d\ude3a":["grinning cat","cat","smile"],"\ud83d\ude38":["grinning cat with smiling eyes","cat","smile"],"\ud83d\ude39":["cat with tears of joy","cat","laughing"],"\ud83d\ude3b":["smiling cat with heart-eyes","cat","love"],"\ud83d\ude3c":["cat with wry smile","cat","smirk"],"\ud83d\ude3d":["kissing cat","cat","kiss"],"\ud83d\ude40":["weary cat","cat","weary"],"\ud83d\ude3f":["crying cat","cat","cry","sad"],"\ud83d\ude3e":["pouting cat","cat","pout"],"\ud83d\udc4b":["waving hand","wave","hello","hi","goodbye"],"\ud83e\udd1a":["raised back of hand","hand"],"\ud83d\udd90":["hand with fingers splayed","hand","fingers"],"\u270b":["raised hand","hand","stop","high five"],"\ud83d\udd96":["vulcan salute","spock","live long"],"\ud83d\udc4c":["ok hand","ok","okay"],"\ud83e\udd0c":["pinched fingers","fingers"],"\ud83e\udd0f":["pinching hand","pinch","small"],"\u270c\ufe0f":["victory hand","victory","peace","two"],"\ud83e\udd1e":["crossed fingers","fingers crossed","luck"],"\ud83e\udd1f":["love-you gesture","love","rock"],"\ud83e\udd18":["sign of the horns","rock","metal","horns"],"\ud83e\udd19":["call me hand","call","phone"],"\ud83d\udc48":["backhand index pointing left","point","left"],"\ud83d\udc49":["backhand index pointing right","point","right"],"\ud83d\udc46":["backhand index pointing up","point","up"],"\ud83d\udd95":["middle finger","finger","rude"],"\ud83d\udc47":["backhand index pointing down","point","down"],"\u261d\ufe
10f":["index pointing up","point","up"],"\ud83d\udc4d":["thumbs up","thumbs up","like","good"],"\ud83d\udc4e":["thumbs down","thumbs down","dislike","bad"],"\u270a":["raised fist","fist","power"],"\ud83d\udc4a":["oncoming fist","fist","punch"],"\ud83e\udd1b":["left-facing fist","fist","left"],"\ud83e\udd1c":["right-facing fist","fist","right"],"\ud83d\udc4f":["clapping hands","clap","applause"],"\ud83d\ude4c":["raising hands","hands","celebration","hallelujah"],"\ud83d\udc50":["open hands","hands","open"],"\ud83e\udd32":["palms up together","hands","prayer"],"\ud83e\udd1d":["handshake","handshake","deal","agreement"],"\ud83d\ude4f":["folded hands","pray","please","thank you"],"\u270d\ufe0f":["writing hand","write","pen"],"\ud83d\udcaa":["flexed biceps","muscle","strong","bicep"],"\ud83e\uddbe":["mechanical arm","arm","robot"],"\ud83e\uddbf":["mechanical leg","leg","robot"],"\ud83e\uddb5":["leg","leg"],"\ud83e\uddb6":["foot","foot"],"\ud83d\udc42":["ear","ear"],"\ud83e\uddbb":["ear with hearing aid","ear","hearing aid"],"\ud83d\udc43":["nose","nose"],"\ud83e\udde0":["brain","brain"],"\ud83e\udec0":["anatomical heart","heart","anatomy"],"\ud83e\udec1":["lungs","lungs"],"\ud83e\uddb7":["tooth","tooth"],"\ud83e\uddb4":["bone","bone"],"\ud83d\udc40":["eyes","eyes","see"],"\ud83d\udc41\ufe0f":["eye","eye","see"],"\ud83d\udc45":["tongue","tongue"],"\ud83d\udc44":["mouth","mouth","lips"],"\ud83d\udc76":["baby","baby","infant"],"\ud83e\uddd2":["child","child","kid"],"\ud83d\udc66":["boy","boy"],"\ud83d\udc67":["girl","girl"],"\ud83e\uddd1":["person","person","adult"],"\ud83d\udc71":["person: blond hair","blond","person"],"\ud83d\udc68":["man","man","male"],"\ud83e\uddd4":["man: beard","beard","man"],"\ud83d\udc68\u200d\ud83e\uddb0":["man: red hair","red hair","man"],"\ud83d\udc68\u200d\ud83e\uddb1":["man: curly hair","curly hair","man"],"\ud83d\udc68\u200d\ud83e\uddb3":["man: white hair","white hair","man"],"\ud83d\udc68\u200d\ud83e\uddb2":["man: bald","bald","man"],"\ud83d\udc69":["woman","woman","female"],"\ud83d\udc69\u200d\ud83e\uddb0":["woman: red hair","red hair","woman"],"\ud83e\uddd1\u200d\ud83e\uddb0":["person: red hair","red hair","person"],"\ud83d\udc69\u200d\ud83e\uddb1":["woman: curly hair","curly hair","woman"],"\ud83e\uddd1\u200d\ud83e\uddb1":["person: curly hair","curly hair","person"],"\ud83d\udc69\u200d\ud83e\uddb3":["woman: white hair","white hair","woman"],"\ud83e\uddd1\u200d\ud83e\uddb3":["person: white hair","white hair","person"],"\ud83d\udc69\u200d\ud83e\uddb2":["woman: bald","bald","woman"],"\ud83e\uddd1\u200d\ud83e\uddb2":["person: bald","bald","person"],"\ud83d\udc71\u200d\u2640\ufe0f":["woman: blond hair","blond","woman"],"\ud83d\udc71\u200d\u2642\ufe0f":["man: blond hair","blond","man"],"\ud83e\uddd3":["older person","old","elderly"],"\ud83d\udc74":["old man","old man","elderly"],"\ud83d\udc75":["old woman","old woman","elderly"],"\ud83d\ude4d":["person frowning","frown","sad"],"\ud83d\ude4d\u200d\u2642\ufe0f":["man frowning","frown","man","sad"],"\ud83d\ude4d\u200d\u2640\ufe0f":["woman frowning","frown","woman","sad"],"\ud83d\ude4e":["person pouting","pout"],"\ud83d\ude4e\u200d\u2642\ufe0f":["man pouting","pout","man"],"\ud83d\ude4e\u200d\u2640\ufe0f":["woman pouting","pout","woman"],"\ud83d\ude45":["person gesturing no","no","stop"],"\ud83d\ude45\u200d\u2642\ufe0f":["man gesturing no","no","man","stop"],"\ud83d\ude45\u200d\u2640\ufe0f":["woman gesturing no","no","woman","stop"],"\ud83d\ude46":["person gesturing ok","ok","okay"],"\ud83d\ude46\u200d\u2642\ufe0f":["man gesturing ok","ok","man","okay"],"\ud83d\ude46\u200d\u2640\ufe0f":["woman gesturing ok","ok","woman","okay"],"\ud83d\udc81":["person tipping hand","information","help"],"\ud83d\udc81\u200d\u2642\ufe0f":["man tipping hand","information","man","help"],"\ud83d\udc81\u200d\u2640\ufe0f":["woman tipping hand","information","woman","help"],"\ud83d\ude4b":["person raising hand","raise hand","question"],"\ud83d\ude4b\u200d\u2642\ufe0f":["man raising hand","raise hand","man","question"],"\ud83d\ude4b\u200d\u2640\ufe0f":["woman raising hand","raise hand","woman","question"],"\ud83e\uddcf":["deaf person","deaf"],"\ud83e\uddcf\u200d\u2642\ufe0f":["deaf man","deaf","man"],"\ud83e\uddcf\u200d\u2640\ufe0f":["deaf woman","deaf","woman"],"\ud83e\udd26":["person facepalming","facepalm","disappointed"],"\ud83e\udd26\u200d\u2642\ufe0f":["man facepalming","facepalm","man","disappointed"],"\ud83e\udd26\u200d\u2640\ufe0f":["woman facepalming","facepalm","woman","disappointed"],"\ud83e\udd37":["person shrugging","shrug","dont know"],"\ud83e\udd37\u200d\u2642\ufe0f":["man shrugging","shrug","man","dont know"],"\ud83e\udd37\u200d\u2640\ufe0f":["woman shrugging","shrug","woman","dont know"],"\ud83d\ude47":["person bowing","bow","respect"],"\ud83d\ude47\u200d\u2642\ufe0f":["man bowing","bow","man","respect"],"\ud83d\ude47\u200d\u2640\ufe0f":["woman bowing","bow","woman","respect"],"\ud83e\uddd1\u200d\u2695\ufe0f":["health worker","doctor","nurse","medical"],"\ud83d\udc68\u200d\u2695\ufe0f":["man health worker","doctor","man","medical"],"\ud83d\udc69\u200d\u2695\ufe0f":["woman health worker","doctor","woman","medical"],"\ud83e\uddd1\u200d\ud83c\udf93":["student","student","graduation"],"\ud83d\udc68\u200d\ud83c\udf93":["man student","student","man","graduation"],"\ud83d\udc69\u200d\ud83c\udf93":["woman student","student","woman","graduation"],"\ud83e\uddd1\u200d\ud83c\udfeb":["teacher","teacher","professor"],"\ud83d\udc68\u200d\ud83c\udfeb":["man teacher","teacher","man","professor"],"\ud83d\udc69\u200d\ud83c\udfeb":["woman teacher","teacher","woman","professor"],"\ud83e\uddd1\u200d\u2696\ufe0f":["judge","judge","law"],"\ud83d\udc68\u200d\u2696\ufe0f":["man judge","judge","man","law"],"\ud83d\udc69\u200d\u2696\ufe0f":["woman judge","judge","woman","law"],"\ud83e\uddd1\u200d\ud83c\udf3e":["farmer","farmer"],"\ud83d\udc68\u200d\ud83c\udf3e":["man farmer","farmer","man"],"\ud83d\udc69\u200d\ud83c\udf3e":["woman farmer","farmer","woman"],"\ud83e\uddd1\u200d\ud83c\udf73":["cook","cook","chef"],"\ud83d\udc68\u200d\ud83c\udf73":["man cook","cook","man","chef"],"\ud83d\udc69\u200d\ud83c\udf73":["woman cook","cook","woman","chef"],"\ud83e\uddd1\u200d\ud83d\udd27":["mechanic","mechanic","repair"],"\ud83d\udc68\u200d\ud83d\udd27":["man mechanic","mechanic","man","repair"],"\ud83d\udc69\u200d\ud83d\udd27":["woman mechanic","mechanic","woman","repair"],"\ud83e\uddd1\u200d\ud83c\udfed":["factory worker","factory","worker"],"\ud83d\udc68\u200d\ud83c\udfed":["man factory worker","factory","man","worker"],"\ud83d\udc69\u200d\ud83c\udfed":["woman factory worker","factory","woman","worker"],"\ud83e\uddd1\u200d\ud83d\udcbc":["office worker","office","business"],"\ud83d\udc68\u200d\ud83d\udcbc":["man office worker","office","man","business"],"\ud83d\udc69\u200d\ud83d\udcbc":["woman office worker","office","woman","business"],"\ud83e\uddd1\u200d\ud83d\udd2c":["scientist","scientist","research"],"\ud83d\udc68\u200d\ud83d\udd2c":["man scie
1ntist","scientist","man","research"],"\ud83d\udc69\u200d\ud83d\udd2c":["woman scientist","scientist","woman","research"],"\ud83e\uddd1\u200d\ud83d\udcbb":["technologist","technologist","computer","tech"],"\ud83d\udc68\u200d\ud83d\udcbb":["man technologist","technologist","man","computer","tech"],"\ud83d\udc69\u200d\ud83d\udcbb":["woman technologist","technologist","woman","computer","tech"],"\ud83e\uddd1\u200d\ud83c\udfa4":["singer","singer","music"],"\ud83d\udc68\u200d\ud83c\udfa4":["man singer","singer","man","music"],"\ud83d\udc69\u200d\ud83c\udfa4":["woman singer","singer","woman","music"],"\ud83e\uddd1\u200d\ud83c\udfa8":["artist","artist","paint"],"\ud83d\udc68\u200d\ud83c\udfa8":["man artist","artist","man","paint"],"\ud83d\udc69\u200d\ud83c\udfa8":["woman artist","artist","woman","paint"],"\ud83e\uddd1\u200d\u2708\ufe0f":["pilot","pilot","airplane"],"\ud83d\udc68\u200d\u2708\ufe0f":["man pilot","pilot","man","airplane"],"\ud83d\udc69\u200d\u2708\ufe0f":["woman pilot","pilot","woman","airplane"],"\ud83e\uddd1\u200d\ud83d\ude80":["astronaut","astronaut","space"],"\ud83d\udc68\u200d\ud83d\ude80":["man astronaut","astronaut","man","space"],"\ud83d\udc69\u200d\ud83d\ude80":["woman astronaut","astronaut","woman","space"],"\ud83e\uddd1\u200d\ud83d\ude92":["firefighter","firefighter","fire"],"\ud83d\udc68\u200d\ud83d\ude92":["man firefighter","firefighter","man","fire"],"\ud83d\udc69\u200d\ud83d\ude92":["woman firefighter","firefighter","woman","fire"],"\ud83d\udc6e":["police officer","police","cop"],"\ud83d\udc6e\u200d\u2642\ufe0f":["man police officer","police","man","cop"],"\ud83d\udc6e\u200d\u2640\ufe0f":["woman police officer","police","woman","cop"],"\ud83d\udd75\ufe0f":["detective","detective","spy"],"\ud83d\udd75\ufe0f\u200d\u2642\ufe0f":["man detective","detective","man","spy"],"\ud83d\udd75\ufe0f\u200d\u2640\ufe0f":["woman detective","detective","woman","spy"],"\ud83d\udc82":["guard","guard"],"\ud83d\udc82\u200d\u2642\ufe0f":["man guard","guard","man"],"\ud83d\udc82\u200d\u2640\ufe0f":["woman guard","guard","woman"],"\ud83e\udd77":["ninja","ninja"],"\ud83d\udc77":["construction worker","construction","worker"],"\ud83d\udc77\u200d\u2642\ufe0f":["man construction worker","construction","man","worker"],"\ud83d\udc77\u200d\u2640\ufe0f":["woman construction worker","construction","woman","worker"],"\ud83e\udd34":["prince","prince","royal"],"\ud83d\udc78":["princess","princess","royal"],"\ud83d\udc73":["person wearing turban","turban"],"\ud83d\udc73\u200d\u2642\ufe0f":["man wearing turban","turban","man"],"\ud83d\udc73\u200d\u2640\ufe0f":["woman wearing turban","turban","woman"],"\ud83d\udc72":["person with skullcap","skullcap"],"\ud83e\uddd5":["woman with headscarf","headscarf","woman"],"\ud83e\udd35":["person in tuxedo","tuxedo","formal"],"\ud83e\udd35\u200d\u2642\ufe0f":["man in tuxedo","tuxedo","man","formal"],"\ud83e\udd35\u200d\u2640\ufe0f":["woman in tuxedo","tuxedo","woman","formal"],"\ud83d\udc70":["person with veil","veil","bride"],"\ud83d\udc70\u200d\u2642\ufe0f":["man with veil","veil","man","bride"],"\ud83d\udc70\u200d\u2640\ufe0f":["woman with veil","veil","woman","bride"],"\ud83e\udd30":["pregnant woman","pregnant","woman"],"\ud83e\udd31":["breast-feeding","breastfeeding","nursing"],"\ud83d\udc7c":["baby angel","angel","baby"],"\ud83c\udf85":["santa claus","santa","christmas"],"\ud83e\udd36":["mrs. claus","mrs claus","santa","christmas"],"\ud83e\uddb8":["superhero","superhero"],"\ud83e\uddb8\u200d\u2642\ufe0f":["man superhero","superhero","man"],"\ud83e\uddb8\u200d\u2640\ufe0f":["woman superhero","superhero","woman"],"\ud83e\uddb9":["supervillain","supervillain","villain"],"\ud83e\uddb9\u200d\u2642\ufe0f":["man supervillain","supervillain","man","villain"],"\ud83e\uddb9\u200d\u2640\ufe0f":["woman supervillain","supervillain","woman","villain"],"\ud83e\uddd9":["mage","mage","wizard","witch"],"\ud83e\uddd9\u200d\u2642\ufe0f":["man mage","mage","man","wizard"],"\ud83e\uddd9\u200d\u2640\ufe0f":["woman mage","mage","woman","witch"],"\ud83e\uddda":["fairy","fairy"],"\ud83e\uddda\u200d\u2642\ufe0f":["man fairy","fairy","man"],"\ud83e\uddda\u200d\u2640\ufe0f":["woman fairy","fairy","woman"],"\ud83e\udddb":["vampire","vampire"],"\ud83e\udddb\u200d\u2642\ufe0f":["man vampire","vampire","man"],"\ud83e\udddb\u200d\u2640\ufe0f":["woman vampire","vampire","woman"],"\ud83e\udddc":["merperson","merperson","mermaid","merman"],"\ud83e\udddc\u200d\u2642\ufe0f":["merman","merman"],"\ud83e\udddc\u200d\u2640\ufe0f":["mermaid","mermaid"],"\ud83e\udddd":["elf","elf"],"\ud83e\udddd\u200d\u2642\ufe0f":["man elf","elf","man"],"\ud83e\udddd\u200d\u2640\ufe0f":["woman elf","elf","woman"],"\ud83e\uddde":["genie","genie"],"\ud83e\uddde\u200d\u2642\ufe0f":["man genie","genie","man"],"\ud83e\uddde\u200d\u2640\ufe0f":["woman genie","genie","woman"],"\ud83e\udddf":["zombie","zombie"],"\ud83e\udddf\u200d\u2642\ufe0f":["man zombie","zombie","man"],"\ud83e\udddf\u200d\u2640\ufe0f":["woman zombie","zombie","woman"],"\ud83d\udc86":["person getting massage","massage"],"\ud83d\udc86\u200d\u2642\ufe0f":["man getting massage","massage","man"],"\ud83d\udc86\u200d\u2640\ufe0f":["woman getting massage","massage","woman"],"\ud83d\udc87":["person getting haircut","haircut"],"\ud83d\udc87\u200d\u2642\ufe0f":["man getting haircut","haircut","man"],"\ud83d\udc87\u200d\u2640\ufe0f":["woman getting haircut","haircut","woman"],"\ud83d\udeb6":["person walking","walking","walk"],"\ud83d\udeb6\u200d\u2642\ufe0f":["man walking","walking","man","walk"],"\ud83d\udeb6\u200d\u2640\ufe0f":["woman walking","walking","woman","walk"],"\ud83e\uddcd":["person standing","standing","stand"],"\ud83e\uddcd\u200d\u2642\ufe0f":["man standing","standing","man","stand"],"\ud83e\uddcd\u200d\u2640\ufe0f":["woman standing","standing","woman","stand"],"\ud83e\uddce":["person kneeling","kneeling","kneel"],"\ud83e\uddce\u200d\u2642\ufe0f":["man kneeling","kneeling","man","kneel"],"\ud83e\uddce\u200d\u2640\ufe0f":["woman kneeling","kneeling","woman","kneel"],"\ud83c\udfc3":["person running","running","run"],"\ud83c\udfc3\u200d\u2642\ufe0f":["man running","running","man","run"],"\ud83c\udfc3\u200d\u2640\ufe0f":["woman running","running","woman","run"],"\ud83d\udc83":["woman dancing","dancing","dance","woman"],"\ud83d\udd7a":["man dancing","dancing","dance","man"],"\ud83d\udd74\ufe0f":["person in suit levitating","levitating","suit"],"\ud83d\udc6f":["people with bunny ears","bunny ears","party"],"\ud83d\udc6f\u200d\u2642\ufe0f":["men with bunny ears","bunny ears","men","party"],"\ud83d\udc6f\u200d\u2640\ufe0f":["women with bunny ears","bunny ears","women","party"],"\ud83e\uddd8":["person in lotus position","yoga","meditation"],"\ud83e\uddd8\u200d\u2642\ufe0f":["man in lotus position","yoga","man","meditation"],"\ud83e\uddd8\u200d\u2640\ufe0f":["woman in lotus position","yoga","woman","meditation"],"\ud83d\udec0":["person taking bath","bath","bathtub"],"\ud83d\udecc":["person in bed","bed","
1sleep"],"\ud83d\udc6d":["women holding hands","women","holding hands"],"\ud83d\udc6b":["woman and man holding hands","couple","holding hands"],"\ud83d\udc6c":["men holding hands","men","holding hands"],"\ud83d\udc8f":["kiss","kiss","couple"],"\ud83d\udc91":["couple with heart","couple","love","heart"],"\ud83d\udc6a":["family","family"],"\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67":["family: man, woman, girl","family"],"\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66":["family: man, woman, girl, boy","family"],"\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66":["family: man, woman, boy, boy","family"],"\ud83d\udc68\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67":["family: man, woman, girl, girl","family"],"\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66":["family: woman, woman, boy","family"],"\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67":["family: woman, woman, girl","family"],"\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66":["family: woman, woman, girl, boy","family"],"\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66":["family: woman, woman, boy, boy","family"],"\ud83d\udc69\u200d\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67":["family: woman, woman, girl, girl","family"],"\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66":["family: man, man, boy","family"],"\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67":["family: man, man, girl","family"],"\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc66":["family: man, man, girl, boy","family"],"\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66":["family: man, man, boy, boy","family"],"\ud83d\udc68\u200d\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc67":["family: man, man, girl, girl","family"],"\ud83d\udc69\u200d\ud83d\udc66":["family: woman, boy","family"],"\ud83d\udc69\u200d\ud83d\udc67":["family: woman, girl","family"],"\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc66":["family: woman, girl, boy","family"],"\ud83d\udc69\u200d\ud83d\udc66\u200d\ud83d\udc66":["family: woman, boy, boy","family"],"\ud83d\udc69\u200d\ud83d\udc67\u200d\ud83d\udc67":["family: woman, girl, girl","family"],"\ud83d\udc68\u200d\ud83d\udc66":["family: man, boy","family"],"\ud83d\udc68\u200d\ud83d\udc67":["family: man, girl","family"],"\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc66":["family: man, girl, boy","family"],"\ud83d\udc68\u200d\ud83d\udc66\u200d\ud83d\udc66":["family: man, boy, boy","family"],"\ud83d\udc68\u200d\ud83d\udc67\u200d\ud83d\udc67":["family: man, girl, girl","family"],"\u26bd":["soccer ball","soccer","football"],"\ud83c\udfc0":["basketball","basketball"],"\ud83c\udfc8":["american football","football","american football"],"\u26be":["baseball","baseball"],"\ud83e\udd4e":["softball","softball"],"\ud83c\udfbe":["tennis","tennis"],"\ud83c\udfd0":["volleyball","volleyball"],"\ud83c\udfc9":["rugby football","rugby"],"\ud83e\udd4f":["flying disc","frisbee","disc"],"\ud83c\udfb1":["pool 8 ball","pool","8 ball","billiards"],"\ud83c\udfd3":["ping pong","ping pong","table tennis"],"\ud83c\udff8":["badminton","badminton"],"\ud83e\udd45":["goal net","goal","hockey"],"\ud83c\udfd2":["ice hockey","hockey","ice hockey"],"\ud83c\udfd1":["field hockey","hockey","field hockey"],"\ud83c\udfcf":["cricket game","cricket"],"\ud83e\udd4d":["lacrosse","lacrosse"],"\ud83c\udff9":["bow and arrow","archery","bow","arrow"],"\ud83c\udfa3":["fishing pole","fishing","fish"],"\ud83e\udd4a":["boxing glove","boxing","glove"],"\ud83e\udd4b":["martial arts uniform","martial arts","karate"],"\ud83c\udfbd":["running shirt","running","shirt"],"\ud83d\udef9":["skateboard","skateboard"],"\ud83d\udef7":["sled","sled","sledge"],"\u26f8\ufe0f":["ice skate","ice skate","skating"],"\ud83e\udd4c":["curling stone","curling"],"\ud83c\udfbf":["skis","skis","skiing"],"\u26f7\ufe0f":["skier","skier","skiing"],"\ud83c\udfc2":["snowboarder","snowboarder","snowboarding"],"\ud83c\udfcb\ufe0f":["person lifting weights","weightlifting","gym"],"\ud83e\udd3c":["people wrestling","wrestling"],"\ud83e\udd38":["person cartwheeling","cartwheel","gymnastics"],"\ud83e\udd3a":["person fencing","fencing","sword"],"\u26f9\ufe0f":["person bouncing ball","basketball","bounce"],"\ud83e\udd3e":["person playing handball","handball"],"\ud83c\udfcc\ufe0f":["person golfing","golf","golfing"],"\ud83c\udfc7":["horse racing","horse racing","racing"],"\ud83c\udfc4":["person surfing","surfing","surf"],"\ud83c\udfca":["person swimming","swimming","swim"],"\ud83d\udea3":["person rowing boat","rowing","boat"],"\ud83e\uddd7":["person climbing","climbing","climb"],"\ud83d\udeb5":["person mountain biking","mountain biking","biking"],"\ud83d\udeb4":["person biking","biking","bike","cycling"],"\ud83c\udfc6":["trophy","trophy","award","winner"],"\ud83e\udd47":["1st place medal","gold","first","medal"],"\ud83e\udd48":["2nd place medal","silver","second","medal"],"\ud83e\udd49":["3rd place medal","bronze","third","medal"],"\ud83c\udfc5":["sports medal","medal"],"\ud83c\udf96\ufe0f":["military medal","medal","military"],"\ud83c\udff5\ufe0f":["rosette","rosette"],"\ud83c\udf97\ufe0f":["reminder ribbon","ribbon"],"\ud83c\udfab":["ticket","ticket"],"\ud83c\udf9f\ufe0f":["admission tickets","tickets"],"\ud83c\udfaa":["cir
1cus tent","circus"],"\ud83e\udd39":["person juggling","juggling","juggler"],"\ud83c\udfad":["performing arts","theater","theatre","drama"],"\ud83e\ude70":["ballet shoes","ballet"],"\ud83c\udfa8":["artist palette","art","paint","palette"],"\ud83c\udfac":["clapper board","movie","film","cinema"],"\ud83c\udfa4":["microphone","microphone","mic","singing"],"\ud83c\udfa7":["headphone","headphones","music"],"\ud83c\udfbc":["musical score","music","score"],"\ud83c\udfb9":["piano","piano","keyboard"],"\ud83e\udd41":["drum","drum","drums"],"\ud83c\udfb7":["saxophone","saxophone","sax"],"\ud83c\udfba":["trumpet","trumpet"],"\ud83c\udfb8":["guitar","guitar"],"\ud83e\ude95":["banjo","banjo"],"\ud83c\udfbb":["violin","violin"],"\ud83c\udfb2":["game die","dice","die"],"\u265f\ufe0f":["chess pawn","chess","pawn"],"\ud83c\udfaf":["direct hit","target","dart","bullseye"],"\ud83c\udfb3":["bowling","bowling"],"\ud83c\udfae":["video game","video game","gaming","controller"],"\ud83c\udfb0":["slot machine","slot machine","casino"],"\ud83e\udde9":["puzzle piece","puzzle","jigsaw"],"\ud83d\ude97":["automobile","car","auto"],"\ud83d\ude95":["taxi","taxi","cab"],"\ud83d\ude99":["sport utility vehicle","suv","car"],"\ud83d\ude8c":["bus","bus"],"\ud83d\ude8e":["trolleybus","trolley","bus"],"\ud83c\udfce\ufe0f":["racing car","racing car","race car"],"\ud83d\ude93":["police car","police car","cop car"],"\ud83d\ude91":["ambulance","ambulance"],"\ud83d\ude92":["fire engine","fire truck","fire engine"],"\ud83d\ude90":["minibus","minibus","van"],"\ud83d\ude9a":["delivery truck","truck","delivery"],"\ud83d\ude9b":["articulated lorry","truck","lorry"],"\ud83d\ude9c":["tractor","tractor"],"\ud83d\udef4":["kick scooter","scooter"],"\ud83d\udeb2":["bicycle","bike","bicycle"],"\ud83d\udef5":["motor scooter","scooter","motorcycle"],"\ud83c\udfcd\ufe0f":["motorcycle","motorcycle","motorbike"],"\ud83d\udea8":["police car light","police","siren"],"\ud83d\ude94":["oncoming police car","police car"],"\ud83d\ude8d":["oncoming bus","bus"],"\ud83d\ude98":["oncoming automobile","car"],"\ud83d\ude96":["oncoming taxi","taxi"],"\ud83d\udea1":["aerial tramway","tramway","cable c
1ar"],"\ud83d\udea0":["mountain cableway","cable car"],"\ud83d\ude9f":["suspension railway","railway"],"\ud83d\ude83":["tram car","tram"],"\ud83d\ude8b":["tram","tram"],"\ud83d\ude9e":["mountain railway","railway"],"\ud83d\ude9d":["monorail","monorail"],"\ud83d\ude84":["high-speed train","bullet train","train"],"\ud83d\ude85":["bullet train","bullet train","train"],"\ud83d\ude88":["light rail","light rail","train"],"\ud83d\ude82":["locomotive","steam locomotive","train"],"\ud83d\ude86":["train","train"],"\ud83d\ude87":["metro","metro","subway","underground"],"\ud83d\ude8a":["tram","tram"],"\ud83d\ude89":["station","station","train station"],"\u2708\ufe0f":["airplane","airplane","plane","flight"],"\ud83d\udeeb":["airplane departure","airplane","departure"],"\ud83d\udeec":["airplane arrival","airplane","arrival"],"\ud83d\udee9\ufe0f":["small airplane","small airplane","plane"],"\ud83d\udcba":["seat","seat","airplane seat"],"\ud83d\ude80":["rocket","rocket","space"],"\ud83d\ude81":["helicopter","helicopter"],"\ud83d\udef8":["flying saucer","ufo","alien"],"\ud83d\udea4":["speedboat","speedboat","boat"],"\u26f5":["sailboat","sailboat","sail"],"\ud83d\udee5\ufe0f":["motor boat","motorboat","boat"],"\ud83d\udea2":["ship","ship","boat"],"\u26f4\ufe0f":["ferry","ferry"],"\ud83d\udef3\ufe0f":["passenger ship","cruise ship","ship"],"\ud83c\udfe0":["house","house","home"],"\ud83c\udfe1":["house with garden","house","home","garden"],"\ud83c\udfd8\ufe0f":["house buildings","houses","neighborhood"],"\ud83c\udfda\ufe0f":["derelict house","house","abandoned"],"\ud83c\udfd7\ufe0f":["building construction","construction","building"],"\ud83c\udfed":["factory","factory"],"\ud83c\udfe2":["office building","office","building"],"\ud83c\udfec":["department store","store","shopping"],"\ud83c\udfe3":["japanese post office","post office"],"\ud83c\udfe4":["post office","post office"],"\ud83c\udfe5":["hospital","hospital"],"\ud83c\udfe6":["bank","bank"],"\ud83c\udfe8":["hotel","hotel"],"\ud83c\udfea":["convenience store","store","convenience"],"\ud83c\udfeb":["school","school"],"\ud83c\udfe9":["love hotel","hotel"],"\ud83d\udc92":["wedding","wedding","chapel"],"\ud83c\udfdb\ufe0f":["classical building","building","classical"],"\u26ea":["church","church"],"\ud83d\udd4c":["mosque","mosque"],"\ud83d\udd4d":["synagogue","synagogue"],"\ud83d\udd4b":["kaaba","kaaba"],"\u26e9\ufe0f":["shinto shrine","shrine"],"\ud83d\udee4\ufe0f":["railway track","railway","track"],"\ud83d\udee3\ufe0f":["motorway","highway","road"],"\ud83c\udf91":["moon viewing ceremony","moon"],"\ud83c\udf05":["sunrise","sunrise"],"\ud83c\udf04":["sunrise over mountains","sunrise","mountains"],"\ud83c\udf20":["shooting star","shooting star","star"],"\ud83c\udf87":["sparkler","sparkler"],"\ud83c\udf86":["fireworks","fireworks"],"\ud83c\udf07":["sunset","sunset"],"\ud83c\udf06":["cityscape at dusk","city","dusk"],"\ud83c\udfd9\ufe0f":["cityscape","city","urban"],"\ud83c\udf03":["night with stars","night","stars"],"\ud83c\udf0c":["milky way","milky way","galaxy"],"\ud83c\udf09":["bridge at night","bridge"],"\ud83c\udf01":["foggy","fog"],"\u231a":["watch","watch","time"],"\ud83d\udcf1":["mobile phone","phone","mobile","cellphone"],"\ud83d\udcf2":["mobile phone with arrow","phone","call"],"\ud83d\udcbb":["laptop","laptop","computer"],"\u2328\ufe0f":["keyboard","keyboard"],"\ud83d\udda5\ufe0f":["desktop computer","computer","desktop"],"\ud83d\udda8\ufe0f":["printer","printer"],"\ud83d\uddb1\ufe0f":["computer mouse","mouse","computer"],"\ud83d\uddb2\ufe0f":["trackball","trackball"],"\ud83d\udd79\ufe0f":["joystick","joystick","game"],"\ud83d\udddc\ufe0f":["clamp","clamp"],"\ud83d\udcbe":["floppy disk","floppy disk","save"],"\ud83d\udcbf":["optical disk","cd","dvd"],"\ud83d\udcc0":["dvd","dvd"],"\ud83d\udcfc":["videocassette","vhs","tape"],"\ud83d\udcf7":["camera","camera","photo"],"\ud83d\udcf8":["camera with flash","camera","photo","flash"],"\ud83d\udcf9":["video camera","video camera","video"],"\ud83c\udfa5":["movie camera","movie camera","film"],"\ud83d\udcfd\ufe0f":["film projector","projector","film"],"\ud83c\udf9e\ufe0f":["film frames","film"],"\ud83d\udcde":["telephone receiver","phone","telephone"],"\u260e\ufe0f":["telephone","phone","telephone"],"\ud83d\udcdf":["pager","pager"],"\ud83d\udce0":["fax machine","fax"],"\ud83d\udcfa":["television","tv","television"],"\ud83d\udcfb":["radio","radio"],"\ud83c\udf99\ufe0f":["studio microphone","microphone","mic"],"\ud83c\udf9a\ufe0f":["level slider","slider","audio"],"\ud83c\udf9b\ufe0f":["control knobs","knobs","audio"],"\u23f1\ufe0f":["stopwatch","stopwatch","time"],"\u23f2\ufe0f":["timer clock","timer","time"],"\u23f0":["alarm clock","alarm","clock","time"],"\ud83d\udd70\ufe0f":["mantelpiece clock","clock"],"\u231b":["hourglass done","hourglass","time"],"\u23f3":["hourglass not done","hourglass","time"],"\ud83d\udce1":["satellite antenna","satellite","antenna"],"\ud83d\udd0b":["battery","battery"],"\ud83d\udd0c":["electric plug","plug","electric"],"\ud83d\udca1":["light bulb","light bulb","idea","bulb"],"\ud83d\udd26":["flashlight","flashlight","torch"],"\ud83d\udd6f\ufe0f":["candle","candle"],"\ud83e\ude94":["diya lamp","lamp","diya"],"\ud83e\uddef":["fire extinguisher","fire extinguisher"],"\ud83d\udee2\ufe0f":["oil drum","oil","drum"],"\ud83d\udcb8":["money with wings","money","flying money"],"\ud83d\udcb5":["dollar banknote","dollar","money"],"\ud83d\udcb4":["yen banknote","yen","money"],"\ud83d\udcb6":["euro banknote","euro","money"],"\ud83d\udcb7":["pound banknote","pound","money"],"\ud83d\udcb0":["money bag","money","bag"],"\ud83d\udcb3":["credit card","credit card","card"],"\ud83d\udc8e":["gem stone","gem","diamond","jewel"],"\u2696\ufe0f":["balance scale","scale","justice","balance"],"\ud83e\ude9c":["ladder","ladder"],"\ud83e\uddf0":["toolbox","toolbox","tools"],"\ud83e\ude9b":["screwdriver","screwdriver"],"\ud83d\udd27":["wrench","wrench","tool"],"\ud83d\udd28":["hammer","hammer","tool"],"\u2692\ufe0f":["hammer and pick","hammer","pick","tool"],"\ud83d\udee0\ufe0f":["hammer and wrench","hammer","wrench","tool"],"\u26cf\ufe0f":["pick","pick","tool"],"\ud83e\ude9a":["carpentry saw","saw","tool"],"\ud83d\udd29":["nut and bolt","nut","bolt","tool"],"\u2699\ufe0f":["gear","gear","cog"],"\ud83e\udea4":["mouse trap","mouse trap","trap"],"\ud83e\uddf1":["brick","brick"],"\u26d3\ufe0f":["chains","chains"],"\ud83e\uddf2":["magnet","magnet"],"\ud83d\udd2b":["water pistol","water gun","gun"],"\ud83d\udca3":["bomb","bomb"],"\ud83e\udde8":["firecracker","firecracker"],"\ud83e\ude93":["axe","axe","hatchet"],"\ud83d\udd2a":["kitchen knife","knife"],"\ud83d\udde1\ufe0f":["dagger","dagger","sword"],"\u2694\ufe0f":["crossed swords","swords","crossed"],"\ud83d\udee1\ufe0f":["shield","shield"],"\ud83d\udeac":["cigarette","cigarette","smoke"],"\u26b0\ufe0f":["coffin","coffin","death"],"\ud83e\udea6":["headstone","headstone","grave"],"\u26b1\ufe0f":["funeral urn","urn","funeral"],"\ud83c\udffa":["amphora","amphora"],"\ud83d\udd2e":["crystal ball","crystal ball","fortune"],"\ud83d\udcff":["prayer beads","prayer beads","rosary"],"\ud83e\uddff":["nazar amulet","nazar","amulet"],"\ud83d\udc88":["barber pole","barber","pole"],"\u2697\ufe0f":["alembic","alembic","chemistry"],"\ud83d\udd2d":["telescope","telescope"],"\ud83d\udd2c":["microscope","microscope"],"\ud83d\udd73\ufe0f":["hole","hole"],"\ud83e\ude79":["adhesive bandage","bandage","band-aid"],"\ud83e\ude7a":["stethoscope","stethoscope","doctor"],"\ud83d\udc8a":["pill","pill","medicine"],"\ud83d\udc89":["syringe","syringe","injection","vaccine"],"\ud83e\ude78":["drop of blood","blood"],"\ud83e\uddec":["dna","dna"],"\ud83e\udda0":["microbe","microbe","bacteria","virus"],"\ud83e\uddeb":["petri dish","petri dish","bacteria"],"\ud83e\uddea":["test tube","test tube","chemistry"],"\ud83c\udf21\ufe0f":["thermometer","thermometer","temperature"],"\ud83e\uddf9":["broom","broom","clean"],"\ud83e\udea0":["plunger","plunger"],"\ud83e\uddfa":["basket","basket"],"\ud83e\uddfb":["roll of paper","toilet paper","paper"],"\ud83d\udebd":["toilet","toilet"],"\ud83d\udebf":["shower","shower"],"\ud83d\udec1":["bathtub","bathtub","bath"],"\ud83e\uddfc":["soap","soap"],"\ud83e\udea5":["toothbrush","toothbrush"],"\ud83e\ude92":["razor","razor"],"\ud83e\uddfd":["sponge","sponge"],"\ud83e\udea3":["bucket","bucket","pail"],"\ud83e\uddf4":["lotion bottle","lotion","bottle"],"\ud83d\udece\ufe0f":["bellhop bell","bell","hotel"],"\ud83d\udd11":["key","key"],"\ud83d\udddd\ufe0f":["old key","key"],"\ud83d\udeaa":["door","door"],"\ud83e\ude91":["chair","chair"],"\ud83d\udecb\ufe0f":["couch and lamp","couch","sofa"],"\ud83d\udecf\ufe0f":["bed","bed"],"\ud83e\uddf8":["teddy bear","teddy bear","bear","toy"],"\ud83e\ude86":["nesting dolls","matryoshka","dolls"],"\ud83d\uddbc\ufe0f":["framed picture","picture","frame"],"\ud83e\ude9e":["mirror","mirror"],"\ud83e\ude9f":["window","window"],"\ud83d\udecd\ufe0f":["shopping bags","shopping","bags"],"\ud83d\uded2":["shopping cart","shopping cart","cart"],"\ud83c\udf81":["wrapped gift","gift","present"],"\ud83c\udf88":["balloon","balloon"],"\ud83c\udf8f":["carp streamer","carp","streamer"],"\ud83c\udf80":["ribbon","ribbon"],"\ud83e\ude84":["magic wand","magic wand","wand"],"\ud83e\ude85":["pinata","pinata"],"\ud83e\udea9":["mirror ball","disco ball","mirror ball"],"\ud83c\udf8a":["confetti ball","confetti","party"],"\ud83c\udf89":["party popper","party","celebration"],"\ud83c\udf8e":["japanese dolls","dolls"],"\ud83c\udfee":["red paper lantern","lantern"],"\ud83c\udf90":["wind chime","wind chime"],"\ud83e\udde7":["red envelope","red envelope","money"],"\u2709\ufe0f":["envelope","envelope","letter"],"\ud83d\udce9":["envelope with arrow","envelope","email"],"\ud83d\udce8":["incoming envelope","envelope"],"\ud83d\udce7":["e-mail","email","e-mail"],"\ud83d\udc8c":["love letter","love letter","letter"],"\ud83d\udce5":["inbox tray","inbox"],"\ud83d\udce4":["outbox tray","outbox"],"\ud83d\udce6":["package","package","box"],"\ud83c\udff7\ufe0f":["label","label","tag"],"\ud83e\udea7":["placard","placard","sign"],"\ud83d\udcea":["closed mailbox with lowered flag","mailbox"],"\ud83d\udceb":["closed mailbox with raised flag","mailbox"],"\ud83d\udcec":["open mailbox with raised flag","mailbox"],"\ud83d\udced":["open mailbox with lowered flag","mailbox"],"\ud83d\udcee":["postbox","postbox","mailbox"],"\ud83d\udcef":["postal horn","horn"],"\ud83d\udcdc":["scroll","scroll","document"],"\ud83d\udcc3":["page with curl","page","document"],"\ud83d\udcc4":["page facing up","page","document"],"\ud83d\udcd1":["bookmark tabs","bookmarks","tabs"],"\ud83e\uddfe":["receipt","receipt"],"\ud83d\udcca":["bar chart","chart","graph","bar chart"],"\ud83d\udcc8":["chart increasing","chart","graph","increasing"],"\ud83d\udcc9":["chart decreasing","chart","graph","decreasing"],"\ud83d\uddd2\ufe0f":["spiral notepad","notepad","spiral"],"\ud83d\uddd3\ufe0f":["spiral calendar","calendar","spiral"],"\ud83d\udcc6":["tear-off calendar","calendar"],"\ud83d\udcc5":["calendar","calendar"],"\ud83d\uddd1\ufe0f":["wastebasket","trash","delete"],"\ud83d\udcc7":["card index","card","index"],"\ud83d\uddc3\ufe0f":["card file box","file box","card"],"\ud83d\uddf3\ufe0f":["ballot box with ballot","ballot","vote"],"\ud83d\uddc4\ufe0f":["file cabinet","file cabinet","cabinet"],"\ud83d\udccb":["clipboard","clipboard"],"\ud83d\udcc1":["file folder","folder","file"],"\ud83d\udcc2":["open file folder","folder","file"],"\ud83d\uddc2\ufe0f":["card index dividers","dividers","card"],"\ud83d\uddde\ufe0f":["rolled-up newspaper","newspaper"],"\ud83d\udcf0":["newspaper","newspaper"],"\ud83d\udcd3":["notebook","notebook"],"\ud83d\udcd4":["notebook with decorative cover","notebook"],"\ud83d\udcd2":["ledger","ledger","notebook"],"\ud83d\udcd5":["closed book","book"],"\ud83d\udcd7":["green book","book"],"\ud83d\udcd8":["blue book","book"],"\ud83d\udcd9":["orange book","book"],"\ud83d\udcda":["books","books","library"],"\ud83d\udcd6":["open book","book","read"],"\ud83d\udd16":["bookmark","bookmark"],"\ud83e\uddf7":["safety pin","safety pin","pin"],"\ud83d\udd17":["link","link","chain"],"\ud83d\udcce":["paperclip","paperclip"],"\ud83d\udd87\ufe0f":["linked paperclips","paperclips"],"\ud83d\udcd0":["triangular ruler","ruler","triangle"],"\ud83d\udccf":["straight ruler","ruler","straight"],"\ud83e\uddee":["abacus","abacus"],"\ud83d\udccc":["pushpin","pushpin","pin"],"\ud83d\udccd":["round pushpin","pushpin","pin","location"],"\u2702\ufe0f":["scissors","scissors","cut"],"\ud83d\udd8a\ufe0f":["pen","pen"],"\ud83d\udd8b\ufe0f":["fountain pen","fountain pen","pen"],"\u2712\ufe0f":["black nib","nib","pen"],"\ud83d\udd8c\ufe0f":["paintbrush","paintbrush","brush"],"\ud83d\udd8d\ufe0f":["crayon","crayon"],"\ud83d\udcdd":["memo","memo","note","write"],"\u270f\ufe0f":["pencil","pencil"],"\ud83d\udd0d":["magnifying glass tilted left","search","magnifying glass"],"\ud83d\udd0e":["magnifying glass tilted right","search","magnifying glass"],"\ud83d\udd0f":["locked with pen","locked","pen"],"\ud83d\udd10":["locked with key","locked","key"],"\ud83d\udd12":["locked","locked","lock"],"\ud83d\udd13":["unlocked","unlocked","unlock"],"\u2764\ufe0f":["red heart","heart","love","red"],"\ud83e\udde1":["orange heart","heart","orange"],"\ud83d\udc9b":["yellow heart","heart","yellow"],"\ud83d\udc9a":["green heart","heart","green"],"\ud83d\udc99":["blue heart","heart","blue"],"\ud83d\udc9c":["purple heart","heart","purple"],"\ud83d\udda4":["black heart","heart","black"],"\ud83e\udd0d":["white heart","heart","white"],"\ud83e\udd0e":["brown heart","heart","brown"],"\ud83d\udc94":["broken heart","heart","broken","sad"],"\u2763\ufe0f":["heart exclamation","heart","exclamation"],"\ud83d\udc95":["two hearts","hearts","love"],"\ud83d\udc9e":["revolving hearts","hearts","love"],"\ud83d\udc93":["beating heart","heart","beating"],"\ud83d\udc97":["growing heart","heart","growing"],"\ud83d\udc96":["sparkling heart","heart","sparkling"],"\ud83d\udc98":["heart with arrow","heart","arrow","cupid"],"\ud83d\udc9d":["heart with ribbon","heart","ribbon","gift"],"\ud83d\udc9f":["heart decoration","heart"],"\u262e\ufe0f":["peace symbol","peace"],"\u271d\ufe0f":["latin cross","cross","christian"],"\u262a\ufe0f":["star and crescent","islam","muslim"],"\ud83d\udd49\ufe0f":["om","om","hindu"],"\u2638\ufe0f":["wheel of dharma","buddhism","dharma"],"\u2721\ufe0f":["star of david","judaism","jewish"],"\ud83d\udd2f":["dotted six-pointed star","star","judaism"],"\ud83d\udd4e":["menorah","menorah","hanukkah"],"\u262f\ufe0f":["yin yang","yin yang","taoism"],"\u2626\ufe0f":["orthodox cross","cross","orthodox"],"\ud83d\uded0":["place of worship","worship","religion"],"\u26ce":["ophiuchus","ophiuchus","zodiac"],"\u2648":["aries","aries","zodiac"],"\u2649":["taurus","taurus","zodiac"],"\u264a":["gemini","gemini","zodiac"],"\u264b":["cancer","cancer","zodiac"],"\u264c":["leo","leo","zodiac"],"\u264d":["virgo","virgo","zodiac"],"\u264e":["libra","libra","zodiac"],"\u264f":["scorpio","scorpio","zodiac"],"\u2650":["sagittarius","sagittarius","zodiac"],"\u2651":["capricorn","capricorn","zodiac"],"\u2652":["aquarius","aquarius","zodiac"],"\u2653":["pisces","pisces","zodiac"],"\ud83c\udd94":["id button","id"],"\u269b\ufe0f":["atom symbol","atom","science"],"\ud83c\ude51":["japanese acceptable button","acceptable"],"\u2622\ufe0f":["radioactive","radioactive","nuclear"],"\u2623\ufe0f":["biohazard","biohazard","danger"],"\ud83d\udcf4":["mobile phone off","phone off"],"\ud83d\udcf3":["vibration mode","vibration"],"\ud83c\ude36":["japanese not free of charge button","not free"],"\ud83c\ude1a":["japanese free of charge button","free"],"\ud83c\ude38":["japanese application button","application"],"\ud83c\ude3a":["japanese open for business button","open"],"\ud83c\ude37\ufe0f":["japanese monthly amount button","monthly"],"\u2734\ufe0f":["eight-pointed star","star"],"\ud83c\udd9a":["vs button","vs","versus"],"\ud83d\udcae":["white flower","flower"],"\ud83c\ude50":["japanese bargain button","bargain"],"\u3299\ufe0f":["japanese secret button","secret"],"\u3297\ufe0f":["japanese congratulations button","congratulations"],"\ud83c\ude34":["japanese passing grade button","passing"],"\ud83c\ude35":["japanese no vacancy button","no vacancy"],"\ud83c\ude39":["japanese discount button","discount"],"\ud83c\ude32":[
1"japanese prohibited button","prohibited"],"\ud83c\udd70\ufe0f":["a button blood type","a","blood type"],"\ud83c\udd71\ufe0f":["b button blood type","b","blood type"],"\ud83c\udd8e":["ab button blood type","ab","blood type"],"\ud83c\udd91":["cl button","cl","clear"],"\ud83c\udd7e\ufe0f":["o button blood type","o","blood type"],"\ud83c\udd98":["sos button","sos","help","emergency"],"\u274c":["cross mark","cross","no","wrong"],"\u2b55":["heavy large circle","circle","yes","ok"],"\ud83d\uded1":["stop sign","stop"],"\u26d4":["no entry","no entry","forbidden"],"\ud83d\udcdb":["name badge","badge","name"],"\ud83d\udeab":["prohibited","prohibited","forbidden"],"\ud83d\udcaf":["hundred points","100","hundred","perfect"],"\ud83d\udca2":["anger symbol","anger","angry"],"\u2668\ufe0f":["hot springs","hot springs","hot"],"\ud83d\udeb7":["no pedestrians","no pedestrians","forbidden"],"\ud83d\udeaf":["no littering","no littering","forbidden"],"\ud83d\udeb3":["no bicycles","no bicycles","forbidden"],"\ud83d\udeb1":["non-potable water","non-potable","water"],"\ud83d\udd1e":["no one under eighteen","18","forbidden","adults only"],"\ud83d\udcf5":["no mobile phones","no phones","forbidden"],"\ud83d\udead":["no smoking","no smoking","forbidden"],"\u2757":["exclamation mark","exclamation","warning"],"\u2753":["question mark","question","?"],"\u2755":["white exclamation mark","exclamation"],"\u2754":["white question mark","question"],"\u203c\ufe0f":["double exclamation mark","exclamation"],"\u2049\ufe0f":["exclamation question mark","exclamation","question"],"\ud83d\udd05":["dim button","dim","low brightness"],"\ud83d\udd06":["bright button","bright","high brightness"],"\u303d\ufe0f":["part alternation mark","alternation"],"\u26a0\ufe0f":["warning","warning","caution"],"\ud83d\udeb8":["children crossing","children","crossing"],"\ud83d\udd31":["trident emblem","trident"],"\u269c\ufe0f":["fleur-de-lis","fleur-de-lis"],"\ud83d\udd30":["japanese symbol for beginner","beginner"],"\u267b\ufe0f":["recycling symbol","recycling","recycle"],"\u2705":["check mark button","check","yes","correct"],"\ud83c\ude2f":["japanese reserved button","reserved"],"\ud83d\udcb9":["chart increasing with yen","chart","yen"],"\u2747\ufe0f":["sparkle","sparkle"],"\u2733\ufe0f":["eight-spoked asterisk","asterisk"],"\u274e":["cross mark button","cross","no","wrong"],"\ud83c\udf10":["globe with meridians","globe","world"],"\ud83d\udca0":["diamond with a dot","diamond"],"\u24c2\ufe0f":["circled m","m","metro"],"\ud83c\udf00":["cyclone","cyclone","hurricane"],"\ud83d\udca4":["zzz","sleep","zzz"],"\ud83c\udfe7":["atm sign","atm","cash"],"\ud83d\udebe":["water closet","wc","toilet"],"\u267f":["wheelchair symbol","wheelchair","accessible"],"\ud83c\udd7f\ufe0f":["p button","parking","p"],"\ud83c\ude33":["japanese vacancy button","vacancy"],"\ud83c\ude02\ufe0f":["japanese service charge button","service charge"],"\ud83d\udec2":["passport control","passport"],"\ud83d\udec3":["customs","customs"],"\ud83d\udec4":["baggage claim","baggage"],"\ud83d\udec5":["left luggage","luggage"],"\ud83d\udeb9":["mens room","mens","men","toilet"],"\ud83d\udeba":["womens room","womens","women","toilet"],"\ud83d\udebc":["baby symbol","baby"],"\ud83d\udebb":["restroom","restroom","toilet"],"\ud83d\udeae":["litter in bin sign","litter","bin"],"\ud83c\udfa6":["cinema","cinema","movie"],"\ud83d\udcf6":["antenna bars","signal","bars"],"\ud83c\ude01":["japanese here button","here"],"\ud83d\udd23":["input symbols","symbols","input"],"\u2139\ufe0f":["information","information","info"],"\ud83d\udd24":["input latin letters","letters","alphabet"],"\ud83d\udd21":["input latin lowercase","lowercase","letters"],"\ud83d\udd20":["input latin uppercase","uppercase","letters"],"\ud83d\udd22":["input numbers","numbers"],"\ud83d\udd1f":["keycap: 10","10","ten"],"\ud83c\udff3\ufe0f":["white flag","white flag","surrender"],"\ud83c\udff4":["black flag","black flag"],"\ud83c\udfc1":["chequered flag","chequered flag","race","finish"],"\ud83d\udea9":["triangular flag","triangular flag","flag"],"\ud83c\udff3\ufe0f\u200d\ud83c\udf08":["rainbow flag","rainbow flag","pride","lgbt"],"\ud83c\udff3\ufe0f\u200d\u26a7\ufe0f":["transgender flag","transgender flag","trans"],"\ud83c\uddfa\ud83c\uddf3":["united nations","un","united nations"],"\ud83c\udde6\ud83c\uddeb":["afghanistan","afghanistan"],"\ud83c\udde6\ud83c\uddfd":["aland islands","aland islands"],"\ud83c\udde6\ud83c\uddf1":["albania","albania"],"\ud83c\udde9\ud83c\uddff":["algeria","alger
1ia"],"\ud83c\udde6\ud83c\uddf8":["american samoa","american samoa"],"\ud83c\udde6\ud83c\udde9":["andorra","andorra"],"\ud83c\udde6\ud83c\uddf4":["angola","angola"],"\ud83c\udde6\ud83c\uddee":["anguilla","anguilla"],"\ud83c\udde6\ud83c\uddf6":["antarctica","antarctica"],"\ud83c\udde6\ud83c\uddec":["antigua and barbuda","antigua and barbuda"],"\ud83c\udde6\ud83c\uddf7":["argentina","argentina"],"\ud83c\udde6\ud83c\uddf2":["armenia","armenia"],"\ud83c\udde6\ud83c\uddfc":["aruba","aruba"],"\ud83c\udde6\ud83c\uddfa":["australia","australia"],"\ud83c\udde6\ud83c\uddf9":["austria","austria"],"\ud83c\udde6\ud83c\uddff":["azerbaijan","azerbaijan"],"\ud83c\udde7\ud83c\uddf8":["bahamas","bahamas"],"\ud83c\udde7\ud83c\udded":["bahrain","bahrain"],"\ud83c\udde7\ud83c\udde9":["bangladesh","bangladesh"],"\ud83c\udde7\ud83c\udde7":["barbados","barbados"],"\ud83c\udde7\ud83c\uddfe":["belarus","belarus"],"\ud83c\udde7\ud83c\uddea":["belgium","belgium"],"\ud83c\udde7\ud83c\uddff":["belize","belize"],"\ud83c\udde7\ud83c\uddef":["benin","benin"],"\ud83c\udde7\ud83c\uddf2":["bermuda","bermuda"],"\ud83c\udde7\ud83c\uddf9":["bhutan","bhutan"],"\ud83c\udde7\ud83c\uddf4":["bolivia","bolivia"],"\ud83c\udde7\ud83c\udde6":["bosnia and herzegovina","bosnia and herzegovina"],"\ud83c\udde7\ud83c\uddfc":["botswana","botswana"],"\ud83c\udde7\ud83c\uddf7":["brazil","brazil"],"\ud83c\uddee\ud83c\uddf4":["british indian ocean territory","british indian ocean territory"],"\ud83c\uddfb\ud83c\uddec":["british virgin islands","british virgin islands"],"\ud83c\udde7\ud83c\uddf3":["brunei","brunei"],"\ud83c\udde7\ud83c\uddec":["bulgaria","bulgaria"],"\ud83c\udde7\ud83c\uddeb":["burkina faso","burkina faso"],"\ud83c\udde7\ud83c\uddee":["burundi","burundi"],"\ud83c\uddf0\ud83c\udded":["cambodia","cambodia"],"\ud83c\udde8\ud83c\uddf2":["cameroon","cameroon"],"\ud83c\udde8\ud83c\udde6":["canada","canada"],"\ud83c\uddee\ud83c\uddf6":["iraq","iraq"],"\ud83c\uddee\ud83c\uddf7":["iran","iran"],"\ud83c\uddee\ud83c\uddea":["ireland","ireland"],"\ud83c\uddee\ud83c\uddf2":["isle of man","isle of man"],"\ud83c\uddee\ud83c\uddf1":["israel","israel"],"\ud83c\uddee\ud83c\uddf9":["italy","italy"],"\ud83c\uddef\ud83c\uddea":["jersey","jersey"],"\ud83c\uddef\ud83c\uddf2":["jamaica","jamaica"],"\ud83c\uddef\ud83c\uddf5":["japan","japan"],"\ud83c\uddef\ud83c\uddf4":["jordan","jordan"],"\ud83c\uddf0\ud83c\uddff":["kazakhstan","kazakhstan"],"\ud83c\uddf0\ud83c\uddea":["kenya","kenya"],"\ud83c\uddf0\ud83c\uddee":["kiribati","kiribati"],"\ud83c\uddf0\ud83c\uddfc":["kuwait","kuwait"],"\ud83c\uddf0\ud83c\uddec":["kyrgyzstan","kyrgyzstan"],"\ud83c\uddf1\ud83c\udde6":["laos","laos"],"\ud83c\uddf1\ud83c\uddfb":["latvia","latvia"],"\ud83c\uddf1\ud83c\udde7":["lebanon","lebanon"],"\ud83c\uddf1\ud83c\uddf8":["lesotho","lesotho"],"\ud83c\uddf1\ud83c\uddf7":["liberia","liberia"],"\ud83c\uddf1\ud83c\uddfe":["libya","libya"],"\ud83c\uddf1\ud83c\uddee":["liechtenstein","liechtenstein"],"\ud83c\uddf1\ud83c\uddf9":["lithuania","lithuania"],"\ud83c\uddf1\ud83c\uddfa":["luxembourg","luxembourg"],"\ud83c\uddf2\ud83c\uddf4":["macao","macao"],"\ud83c\uddf2\ud83c\uddec":["madagascar","madagascar"],"\ud83c\uddf2\ud83c\uddfc":["malawi","malawi"],"\ud83c\uddf2\ud83c\uddfe":["malaysia","malaysia"],"\ud83c\uddf2\ud83c\uddfb":["maldives","maldives"],"\ud83c\uddf2\ud83c\uddf1":["mali","mali"],"\ud83c\uddf2\ud83c\uddf9":["malta","malta"],"\ud83c\uddf2\ud83c\udded":["marshall islands","marshall islands"],"\ud83c\uddf2\ud83c\uddf6":["martinique","martinique"],"\ud83c\uddf2\ud83c\uddf7":["mauritania","mauritania"],"\ud83c\uddf2\ud83c\uddfa":["mauritius","mauritius"],"\ud83c\uddfe\ud83c\uddf9":["mayotte","mayotte"],"\ud83c\uddf2\ud83c\uddfd":["mexico","mexico"],"\ud83c\uddeb\ud83c\uddf2":["micronesia","micronesia"],"\ud83c\uddf2\ud83c\udde9":["moldova","moldova"],"\ud83c\uddf2\ud83c\udde8":["monaco","monaco"],"\ud83c\uddf2\ud83c\uddf3":["mongolia","mongolia"],"\ud83c\uddf2\ud83c\uddea":["montenegro","montenegro"],"\ud83c\uddf2\ud83c\uddf8":["montserrat","montserrat"],"\ud83c\uddf2\ud83c\udde6":["morocco","morocco"],"\ud83c\uddf2\ud83c\uddff":["mozambique","mozambique"],"\ud83c\uddf2\ud83c\uddf2":["myanmar","myanmar"],"\ud83c\uddf3\ud83c\udde6":["namibia","namibia"],"\ud83c\uddf3\ud83c\uddf7":["nauru","nauru"],"\ud83c\uddf3\ud83c\uddf5":["nepal","nepal"],"\ud83c\uddf3\ud83c\uddf1":["netherlands","netherlands"],"\ud83c\uddf3\ud83c\udde8":["new caledonia","new caledonia"],"\ud83c\uddf3\ud83c\uddff":["new zealand","new zealand"],"\ud83c\uddf3\ud83c\uddee":["nicaragua","nicaragua"],"\ud83c\uddf3\ud83c\uddea":["niger","niger"],"\ud83c\uddf3\ud83c\uddec":["nigeria","nigeria"],"\ud83c\uddf3\ud83c\uddfa":["niue","niue"],"\ud83c\uddf3\ud83c\uddeb":["norfolk island","norfolk island"],"\ud83c\uddf0\ud83c\uddf5":["north korea","north korea"],"\ud83c\uddf2\ud83c\uddf0":["north macedonia","north macedonia"],"\ud83c\uddf2\ud83c\uddf5":["northern mariana islands","northern mariana islands"],"\ud83c\uddf3\ud83c\uddf4":["norway","norway"],"\ud83c\uddf4\ud83c\uddf2":["oman","oman"],"\ud83c\uddf5\ud83c\uddf0":["pakistan","pakistan"],"\ud83c\uddf5\ud83c\uddfc":["palau","palau"],"\ud83c\uddf5\ud83c\uddf8":["palestinian territories","palestinian territories"],"\ud83c\uddf5\ud83c\udde6":["panama","panama"],"\ud83c\uddf5\ud83c\uddec":["papua new guinea","papua new guinea"],"\ud83c\uddf5\ud83c\uddfe":["paraguay","paraguay"],"\ud83c\uddf5\ud83c\uddea":["peru","peru"],"\ud83c\uddf5\ud83c\udded":["philippines","philippines"],"\ud83c\uddf5\ud83c\uddf3":["pitcairn","pitcairn"],"\ud83c\uddf5\ud83c\uddf1":["poland","poland"],"\ud83c\uddf5\ud83c\uddf9":["portugal","portugal"],"\ud83c\uddf5\ud83c\uddf7":["puerto rico","puerto rico"],"\ud83c\uddf6\ud83c\udde6":["qatar","qatar"],"\ud83c\uddf7\ud83c\uddea":["reunion","reunion"],"\ud83c\uddf7\ud83c\uddf4":["romania","romania"],"\ud83c\uddf7\ud83c\uddfa":["russia","russia"],"\ud83c\uddf7\ud83c\uddfc":["rwanda","rwanda"],"\ud83c\uddfc\ud83c\uddf8":["samoa","samoa"],"\ud83c\uddf8\ud83c\uddf2":["san marino","san marino"],"\ud83c\uddf8\ud83c\udde6":["saudi arabia","saudi arabia"],"\ud83c\uddf8\ud83c\uddf3":["senegal","senegal"],"\ud83c\uddf7\ud83c\uddf8":["serbia","serbia"],"\ud83c\uddf8\ud83c\udde8":["seychelles","seychelles"],"\ud83c\uddf8\ud83c\uddf1":["sierra leone","sierra leone"],"\ud83c\uddf8\ud83c\uddec":["singapore","singapore"],"\ud83c\uddf8\ud83c\uddfd":["sint maarten","sint maarten"],"\ud83c\uddf8\ud83c\uddf0":["slovakia","slovakia"],"\ud83c\uddf8\ud83c\uddee":["slovenia","slovenia"],"\ud83c\uddec\ud83c\uddf8":["south georgia and south sandwich islands","south georgia and south sandwich islands"],"\ud83c\uddf8\ud83c\udde7":["solomon islands","solomon islands"],"\ud83c\uddf8\ud83c\uddf4":["somalia","somalia"],"\ud83c\uddff\ud83c\udde6":["south africa","south africa"],"\ud83c\uddf0\ud83c\uddf7":["south korea","south korea"],"\ud83c\uddf8\ud83c\uddf8":["south sudan","south sudan"],"\ud83c\uddea\ud83c\uddf8":["spain","spain"],"\ud83c\uddf1\ud83c\uddf0":["sri lanka","sri lanka"],"\ud83c\udde7\ud83c\uddf1":["saint barthelemy","saint barthelemy"],"\ud83c\uddf8\ud83c\udded":["saint helena","saint helena"],"\ud83c\uddf0\ud83c\uddf3":["saint kitts and nevis","saint kitts and nevis"],"\ud83c\uddf1\ud83c\udde8":["saint lucia","saint lucia"],"\ud83c\uddf5\ud83c\uddf2":["saint pierre and miquelon","saint pierre and miquelon"],"\ud83c\uddfb\ud83c\udde8":["saint vincent and the grenadines","saint vincent and the grenadines"],"\ud83c\uddf8\ud83c\udde9":["sudan","sudan"],"\ud83c\uddf8\ud83c\uddf7":["suriname","suriname"],"\ud83c\uddf8\ud83c\uddea":["sweden","sweden"],"\ud83c\udde8\ud83c\udded":["switzerland","switzerland"],"\ud83c\uddf8\ud83c\uddfe":["syria","syria"],"\ud83c\uddf9\ud83c\uddfc":["taiwan","taiwan"],"\ud83c\uddf9\ud83c\uddef":["tajikistan","tajikistan"],"\ud83c\uddf9\ud83c\uddff":["tanzania","tanzania"],"\ud83c\uddf9\ud83c\udded":["thailand","thailand"],"\ud83c\uddf9\ud83c\uddf1":["timor-leste","timor-leste"],"\ud83c\uddf9\ud83c\uddec":["togo","togo"],"\ud83c\uddf9\ud83c\uddf0":["tokelau","tokelau"],"\ud83c\uddf9\ud83c\uddf4":["tonga","tonga"],"\ud83c\uddf9\ud83c\uddf9":["trinidad and tobago","trinidad and tobago"],"\ud83c\uddf9\ud83c\uddf3":["tunisia","tunisia"],"\ud83c\uddf9\ud83c\uddf7":["turkey","turkey"],"\ud83c\uddf9\ud83c\uddf2":["turkmenistan","turkmenistan"],"\ud83c\uddf9\ud83c\udde8":["turks and caicos islands","turks and caicos islands"],"\ud83c\uddf9\ud83c\uddfb":["tuvalu","tuvalu"],"\ud83c\uddfb\ud83c\uddee":["u.s. virgin islands","u.s. virgin islands"],"\ud83c\uddfa\ud83c\uddec":["uganda","uganda"],"\ud83c\uddfa\ud83c\udde6":["ukraine","ukraine"],"\ud83c\udde6\ud83c\uddea":["united arab emirates","united arab emirates"],"\ud83c\uddec\ud83c\udde7":["united kingdom","united kingdom","uk","britain"],"\ud83c\uddfa\ud83c\uddf8":["united states","united states","usa","america"],"\ud83c\uddfa\ud83c\uddfe":["uruguay","uruguay"],"\ud83c\uddfa\ud83c\uddff":["uzbekistan","uzbekistan"],"\ud83c\uddfb\ud83c\uddfa":["vanuatu","vanuatu"],"\ud83c\uddfb\ud83c\udde6":["vatican city","vatican city"],"\ud83c\uddfb\ud83c\uddea":["venezuela","venezuela"],"\ud83c\uddfb\ud83c\uddf3":["vietnam","vietnam"],"\ud83c\uddfc\ud83c\uddeb":["wallis and futuna","wallis and futuna"],"\ud83c\uddea\ud83c\udded":["western sahara","western sahara"],"\ud83c\uddfe\ud83c\uddea":["yemen","yemen"],"\ud83c\uddff\ud83c\uddf2":["zambia","zambia"],"\ud83c\uddff\ud83c\uddfc":["zimbabwe","zimbabwe"]},Qt=e=>{const t=e.toLowerCase().trim();if(!t)return[];const n=new Set;
1return Object.entries(Ht).forEach(e=>{let r=(0,a.A)(e,2),o=r[0],i=r[1];const s=o.toLowerCase();(s.includes(t)||t.includes(s))&&i.forEach(e=>n.add(e))}),Object.entries(qt).forEach(e=>{let r=(0,a.A)(e,2),o=r[0],i=r[1];const s=o.toLowerCase();(s.includes(t)||t.includes(s))&&i.forEach(e=>n.add(e))}),Object.entries(qt).forEach(e=>{let r=(0,a.A)(e,2),o=r[0],i=r[1];o.toLowerCase().split(/[\s&]+/).forEach(e=>{(e.includes(t)||t.includes(e))&&i.forEach(e=>n.add(e))})}),Object.entries(Kt).forEach(e=>{let r=(0,a.A)(e,2),o=r[0];r[1].forEach(e=>{const r=e.toLowerCase();(r.includes(t)||t.includes(r))&&n.add(o)})}),Array.from(n)},Yt=e=>{let t=e.isOpen,n=e.onClose,r=e.onSelect,o=e.currentEmoji,l=void 0===o?null:o;const d=(0,i.useState)(""),u=(0,a.A)(d,2),m=u[0],p=u[1],g=(0,i.useState)(Object.keys(qt)[0]),h=(0,a.A)(g,2),f=h[0],y=h[1],v=(0,i.useState)(!1),x=(0,a.A)(v,2),b=x[0],w=x[1],k=(0,i.useMemo)(()=>{if(!m.trim()){const e=qt[f]||[];return b?e:e.slice(0,24)}const e=Qt(m);return 0===e.length?[]:b?e:e.slice(0,50)},[m,f,b]),A=(0,i.useMemo)(()=>{if(m.trim()){return Qt(m).length>50}return(qt[f]||[]).length>24},[m,f]),j=e=>{r(e),n()};(0,i.useEffect)(()=>{w(!1)},[f,m]);const N=(0,i.useMemo)(()=>{if(m.trim()){return Qt(m).length}return(qt[f]||[]).length},[m,f]);if(!t)return null;const C="undefined"!==typeof document?document.body:null;return C?(0,s.createPortal)((0,We.jsx)("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black bg-opacity-50",onClick:n,children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-sm max-h-[70vh] flex flex-col",onClick:e=>e.stopPropagation(),children:[(0,We.jsxs)("div",{className:"flex items-center justify-between p-3 border-b border-gray-200",children:[(0,We.jsx)("h3",{className:"text-base font-semibold text-gray-900",children:"Select Emoji"}),(0,We.jsx)("button",{onClick:n,className:"text-gray-400 hover:text-gray-600 transition-colors",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]}),(0,We.jsx)("div",{className:"p-3 border-b border-gray-200",children:(0,We.jsxs)("div",{className:"relative",children:[(0,We.jsx)(_.A,{className:"absolute left-2 top-1/2 transform -translate-y-1/2 h-3.5 w-3.5 text-gray-400"}),(0,We.jsx)("input",{type:"text",placeholder:"Search emojis...",value:m,onChange:e=>p(e.target.value),className:"w-full pl-8 pr-3 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent",autoFocus:!0})]})}),!m&&(0,We.jsx)("div",{className:"flex overflow-x-auto border-b border-gray-200 px-3 py-1.5 space-x-1.5",children:Object.keys(qt).map(e=>(0,We.jsx)("button",{onClick:()=>y(e),className:"px-2.5 py-1 text-xs font-medium whitespace-nowrap rounded-md transition-colors ".concat(f===e?"bg-blue-100 text-blue-700":"text-gray-600 hover:bg-gray-100"),children:e.split(" ")[0]},e))}),(0,We.jsx)("div",{className:"flex-1 overflow-y-auto p-3",children:m?(0,We.jsxs)("div",{children:[(0,We.jsxs)("div",{className:"text-xs text-gray-500 mb-2",children:[k.length," ",1===k.length?"result":"results"]}),(0,We.jsx)("div",{className:"grid grid-cols-10 gap-1",children:k.map((e,t)=>(0,We.jsx)("button",{onClick:()=>j(e),className:"flex items-center justify-center w-full aspect-square text-lg p-1.5 rounded hover:bg-gray-100 transition-colors leading-none ".concat(l===e?"bg-blue-100 ring-2 ring-blue-500":""),title:e,children:(0,We.jsx)("span",{className:"flex items-center justify-center",children:e})},"".concat(e,"-").concat(t)))}),A&&!b&&(0,We.jsxs)("button",{onClick:()=>w(!0),className:"w-full mt-3 py-2 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-md transition-colors font-medium",children:["See More (",N-50," more)"]}),b&&A&&(0,We.jsx)("button",{onClick:()=>w(!1),className:"w-full mt-3 py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-50 rounded-md transition-colors font-medium",children:"Show Less"})]}):(0,We.jsxs)("div",{children:[(0,We.jsx)("div",{className:"grid grid-cols-10 gap-1",children:k.map((e,t)=>(0,We.jsx)("button",{onClick:()=>j(e),className:"flex items-center justify-center w-full aspect-square text-lg p-1.5 rounded hover:bg-gray-100 transition-colors leading-none ".concat(l===e?"bg-blue-100 ring-2 ring-blue-500":""),title:e,children:(0,We.jsx)("span",{className:"flex items-center justify-center",children:e})},"".concat(e,"-").concat(t)))}),A&&!b&&(0,We.jsxs)("button",{onClick:()=>w(!0),className:"w-full mt-3 py-2 text-sm text-blue-600 hover:text-blue-700 hover:bg-blue-50 rounded-md transition-colors font-medium",children:["See More ",m?"":"(".concat(N-24," more)")]}),b&&A&&(0,We.jsx)("button",{onClick:()=>w(!1),className:"w-full mt-3 py-2 text-sm text-gray-600 hover:text-gray-700 hover:bg-gray-50 rounded-md transition-colors font-medium",children:"Show Less"})]})}),(0,We.jsx)("div",{className:"p-3 border-t border-gray-200 text-xs text-gray-500",children:"Click an emoji to select it"})]})}),C):null};var Zt=n(23585),$t=n(1648),Xt=n(41024),en=n(10430),tn=n(80550),nn=n(12475);async function rn(e,t){try{const n=await Q.E.encryptExistingDocumentForWorksp
1ace(e,t);return n?{["workspaceEncryptedResults.".concat(t)]:n}:{}}catch(n){return console.warn("\u26a0\ufe0f Could not prepare workspace ciphertext for assignment:",n),{}}}const on="workspaceLayoutByOrganization";function an(e,t,n,r,i){const s=Array.isArray(e)?e:[],l=Array.isArray(t)?t:[],d=Array.isArray(n)?n:[],c=new Map((r||[]).map(e=>[e.id,e.organizationId]).filter(e=>!!(0,a.A)(e,2)[1])),u=new Set((r||[]).map(e=>e.organizationId).filter(Boolean));u.add(i);const m={},p=e=>{e&&(m[e]||(m[e]={workspaceFolders:[],folderOrder:[],workspaceOrder:[]}))};u.forEach(p);for(const f of s){const e=Array.isArray(f.workspaceIds)?f.workspaceIds:[];if(0===e.length){p(i),m[i].workspaceFolders.push((0,o.A)((0,o.A)({},f),{},{workspaceIds:[]}));continue}const t=new Map;for(const n of e){const e=c.get(n);e&&(t.has(e)||t.set(e,[]),t.get(e).push(n))}for(const n of t){var g=(0,a.A)(n,2);const e=g[0],t=g[1];p(e),m[e].workspaceFolders.push((0,o.A)((0,o.A)({},f),{},{workspaceIds:t}))}}const h={};for(const o of Object.keys(m))h[o]=new Set(m[o].workspaceFolders.map(e=>e.id)),m[o].folderOrder=l.filter(e=>h[o].has(e)),m[o].workspaceOrder=d.filter(e=>c.get(e)===o);return 0===Object.keys(m).length&&(s.length>0||l.length>0||d.length>0)&&(m[i]={workspaceFolders:s,folderOrder:l,workspaceOrder:d}),m}function sn(e){const t=new Set;return(Array.isArray(e)?e:[]).filter(e=>!(!e||t.has(e))&&(t.add(e),!0))}function ln(e,t,n,r){const o=function(e,t){if(!e||!t)return{workspaceFolders:[],folderOrder:[],workspaceOrder:null,archivedWorkspaceIds:[]};const n=e[on],r=n&&"object"===typeof n?n[t]:null;return r&&"object"===typeof r?{workspaceFolders:Array.isArray(r.workspaceFolders)?r.workspaceFolders:[],folderOrder:Array.isArray(r.folderOrder)?r.folderOrder:[],workspaceOrder:Array.isArray(r.workspaceOrder)?r.workspaceOrder:null,archivedWorkspaceIds:Array.isArray(r.archivedWorkspaceIds)?sn(r.archivedWorkspaceIds):[]}:{workspaceFolders:[],folderOrder:[],workspaceOrder:null,archivedWorkspaceIds:[]}}(e,t);if(o.workspaceFolders&&o.workspaceFolders.length>0||o.folderOrder&&o.folderOrder.length>0||Array.isArray(o.workspaceOrder)&&o.workspaceOrder.length>0||!function(e){return!!e&&(Array.isArray(e.workspaceFolders)&&e.workspaceFolders.length>0||Array.isArray(e.folderOrder)&&e.folderOrder.length>0||Array.isArray(e.workspaceOrder)&&e.workspaceOrder.length>0)}(e))return o;const a=an(e.workspaceFolders,e.folderOrder,e.workspaceOrder,n,r)[t];if(!a||"object"!==typeof a)return o;const i=Array.isArray(a.workspaceOrder)?a.workspaceOrder:null;return{workspaceFolders:Array.isArray(a.workspaceFolders)?a.workspaceFolders:[],folderOrder:Array.isArray(a.folderOrder)?a.folderOrder:[],workspaceOrder:i&&i.length>0?i:null,archivedWorkspaceIds:Array.isArray(o.archivedWorkspaceIds)?o.archivedWorkspaceIds:[]}}function dn(e){if(!Array.isArray(e)||e.length<=1)return e||[];const t=new Map;for(const r of e){if("Default Workspace"!==(null===r||void 0===r?void 0:r.name))continue;const e=r.organizationId||"__unknown_org__",n=t.get(e);(!n||!0===r.isDefault&&!0!==n.isDefault)&&t.set(e,r)}const n=new Set;return e.filter(e=>{if("Default Workspace"!==(null===e||void 0===e?void 0:e.name))return!0;const r=e.organizationId||"__unknown_org__",o=t.get(r);return e.id===(null===o||void 0===o?void 0:o.id)&&!n.has(r)&&(n.add(r),!0)})}const cn=e=>{let t=e.children;if("undefined"===typeof document)return null;let n=document.getElementById("modal-root");return n||(n=document.createElement("div"),n.id="modal-root",document.body.appendChild(n)),(0,s.createPortal)(t,n)},un=e=>{let t=e.isOpen,n=e.onClose,r=e.onSubmitWorkspace;const o=(0,i.useState)(""),s=(0,a.A)(o,2),l=s[0],d=s[1];return t?(0,We.jsx)(cn,{children:(0,We.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50",children:(0,We.jsx)("div",{className:"bg-white rounded-lg shadow-lg p-6 w-full max-w-md",children:(0,We.jsxs)("form",{onSubmit:e=>{e.preventDefault(),l.trim()&&(r(l),d(""),n())},children:[(0,We.jsx)("h3",{className:"text-lg font-medium mb-1",children:"Create New Workspace"}),(0,We.jsx)("p",{className:"text-sm text-gray-500 mb-4",children:"Organize documents with folders inside the workspace after you create it."}),(0,We.jsx)("input",{type:"text",className:"w-full border border-gray-300 rounded px-3 py-2 mb-4",placeholder:"Enter workspace name",value:l,onCh
1ange:e=>d(e.target.value),autoFocus:!0}),(0,We.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,We.jsx)("button",{type:"button",onClick:n,className:"px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded",children:"Cancel"}),(0,We.jsx)("button",{type:"submit",className:"px-4 py-2 text-sm text-white bg-blue-500 hover:bg-blue-600 rounded",children:"Create"})]})]})})})}):null},mn=e=>{let t=e.isOpen,n=e.projectToDelete,r=e.documents,o=void 0===r?[]:r,a=e.workspaces,i=void 0===a?[]:a,s=e.activeLinks,l=void 0===s?{}:s,d=e.moveTargetWorkspaceId,c=e.setMoveTargetWorkspaceId,u=e.onConfirmDelete,m=e.onConfirmMoveAndDelete,p=e.onCancel;if(!t||!n)return null;const g=n.id,h=o.filter(e=>(e.workspaceIds||[]).some(e=>String(e)===String(g))),f=h.filter(e=>!0===e.locked),y=i.filter(e=>String(e.id)!==String(g)),v=!!l[g];return(0,We.jsx)(cn,{children:(0,We.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50",children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto",children:[(0,We.jsx)("h3",{className:"text-lg font-medium mb-2",children:"Delete workspace?"}),(0,We.jsx)("p",{className:"text-gray-600 text-sm mb-3",children:0===h.length?"This workspace has no documents. Deleting it only removes the workspace itself.":"Deleting this workspace means all documents in it will no longer be in any workspace and will not appear in the app unless you move them first."}),v&&(0,We.jsx)("p",{className:"text-amber-700 bg-amber-50 border border-amber-200 rounded px-3 py-2 text-sm mb-3",children:"This workspace has a public link. Deleting it will remove the workspace and the link; anyone with the link will no longer be able to access it."}),(0,We.jsxs)("p",{className:"text-gray-600 text-sm mb-3",children:["This workspace has ",(0,We.jsx)("strong",{children:h.length})," document",1!==h.length?"s":"","."]}),f.length>0&&(0,We.jsxs)("div",{className:"mb-3",children:[(0,We.jsxs)("p",{className:"text-gray-700 text-sm font-medium mb-1",children:["The following document",1!==f.length?"s are":" is"," locked and cannot be moved. Unlock ",1!==f.length?"them":"it"," first if you want to move ",1!==f.length?"them":"it",", or ",1!==f.length?"they will":"it will"," be left without a workspace:"]}),(0,We.jsx)("ul",{className:"list-disc list-inside text-sm text-gray-600 ml-1",children:f.map(e=>(0,We.jsx)("li",{children:e.title||e.fileName||"Untitled"},e.id))})]}),y.length>0&&h.length>0&&(0,We.jsxs)("div",{className:"mb-4",children:[(0,We.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Move all documents to another workspace"}),(0,We.jsxs)("select",{className:"w-full border border-gray-300 rounded px-3 py-2 text-sm",value:d||"",onChange:e=>c(e.target.value||null),children:[(0,We.jsx)("option",{value:"",children:"\u2014 Select a workspace \u2014"}),y.map(e=>(0,We.jsx)("option",{value:e.id,children:e.name||e.id},e.id))]})]}),(0,We.jsxs)("div",{className:"flex flex-wrap justify-end gap-2",children:[(0,We.jsx)("button",{type:"button",onClick:p,className:"px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 rounded",children:"Cancel"}),d&&(0,We.jsx)("button",{type:"button",onClick:()=>m(d),className:"px-4 py-2 text-sm text-white bg-blue-500 hover:bg-blue-600 rounded",children:"Move documents and delete workspace"}),(0,We.jsx)("button",{type:"button",onClick:u,className:"px-4 py-2 text-sm text-white bg-red-500 hover:bg-red-600 rounded",children:"Delete workspace"})]})]})})})},pn=e=>{let t=e.workspace,n=e.isArchivedView,r=void 0!==n&&n,o=e.onCreateWorkspace,l=e.onArchive,d=e.onDelete,c=e.visible,m=void 0!==c&&c,g=e.onOpenChange;const h=(0,i.useState)(!1),f=(0,a.A)(h,2),y=f[0],v=f[1],b=(0,i.useState)({top:0,right:0}),w=(0,a.A)(b,2),k=w[0],A=w[1],j=(0,i.useRef)(null),N=(0,i.useCallback)(()=>{v(!1),null===g||void 0===g||g(!1)},[g]);(0,i.useEffect)(()=>{if(!y)return;const e=e=>{const t=document.querySelector('[data-workspace-actions-menu="true"]');!j.current||j.current.contains(e.target)||t&&t.contains(e.target)||N()},t=e=>{"Escape"===e.key&&N()},n=()=>N();return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),window.addEventListener("resize",n),window.addEventListener("scroll",n,!0),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t),window.removeEventListener("resize",n),window.removeEventListener("scroll",n,!0)}},[y,N]);const C="w-full flex items-center gap-2 px-3 py-2 text-sm text-on-surface hover:bg-surface-muted";return(0,We.jsxs)("div",{className:"relative flex-shrink-0 ml-1",onClick:e=>e.stopPropagation(),children:[(0,We.jsx)("button",{ref:j,type:"button",onClick:e=>{var t;if(e.preventDefault(),e.stopPropagation(),y)return void N();const n=null===(t=j.current)||void 0===t?void 0:t.getBoundingClientRect();if(n){const e=window.innerHeight-n.bottom<140?Math.max(8,n.top-132-4):n.bottom+4;A({top:e,right:Math.max(8,window.innerWidth-n.right)})}v(!0),null===g||void 0===g||g(!0)},className:"p-0.5 rounded-brand-sm text-on-surface-subtle hover:text-on-surface hover:bg-surface-sunken transition-opacity ".concat(m||y?"opacity-100":"opacity-0 group-hover:opacity-100"),title:"Workspace options","aria-label":"Options for ".concat(t.name||"workspace"),"aria-haspopup":"menu","aria-expanded":y,children:(0,We.jsx)(u.A,{className:"h-4 w-4",style:{width:"1rem",he
1ight:"1rem",flexShrink:0}})}),y&&(0,s.createPortal)((0,We.jsxs)("div",{role:"menu","data-workspace-actions-menu":"true",className:"fixed z-[9999] w-48 py-1 bg-surface border border-hairline rounded-brand-md shadow-lg",style:{top:"".concat(k.top,"px"),right:"".concat(k.right,"px")},onClick:e=>e.stopPropagation(),children:[(0,We.jsxs)("button",{type:"button",role:"menuitem",className:C,onClick:()=>{N(),null===o||void 0===o||o()},children:[(0,We.jsx)(x.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),"New workspace"]}),(0,We.jsx)("div",{className:"my-1 border-t border-hairline",role:"separator"}),l&&(0,We.jsxs)("button",{type:"button",role:"menuitem",className:C,onClick:()=>{N(),l(t.id,r)},children:[r?(0,We.jsx)(Dt.A,{className:"h-3.5 w-3.5 flex-shrink-0"}):(0,We.jsx)(Pt.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),r?"Unarchive for me":"Archive for me"]}),d&&(0,We.jsxs)("button",{type:"button",role:"menuitem",className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-state-danger hover:bg-state-danger-soft",onClick:e=>{N(),d(e,t)},children:[(0,We.jsx)(p.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),"Delete"]})]}),document.body)]})},gn=e=>{let t=e.workspace,n=e.currentWorkspace,r=e.onSelect,s=e.onDelete,d=e.onArchive,c=e.onCreateWorkspace,u=e.isArchivedView,m=void 0!==u&&u,p=e.unreadCount,h=e.hasActiveLink,f=e.dragOverWorkspace,y=e.onDropDocument,v=e.onDragOverDocument,x=e.onDragLeaveDocument,b=e.onEmojiClick,w=e.selectedDocumentFolderId,k=void 0===w?null:w,A=e.onSelectDocumentFolder,j=e.onCreateDocumentFolder,C=e.canCreateDocumentFolder,S=void 0!==C&&C,E=e.onDropDocumentOnFolder,I=void 0===E?null:E,D=e.dragOverDocumentFolderKey,P=void 0===D?null:D,T=e.onDragOverDocumentFolder,R=void 0===T?null:T,O=e.onDragLeaveDocumentFolder,F=void 0===O?null:O;const L=(0,i.useState)(!1),_=(0,a.A)(L,2),U=_[0],M=_[1],z=(0,i.useState)(!1),B=(0,a.A)(z,2),W=B[0],V=B[1],J=(0,i.useState)(!1),q=(0,a.A)(J,2),H=q[0],G=q[1],K=(0,i.useState)(""),Q=(0,a.A)(K,2),Y=Q[0],Z=Q[1],$=(0,i.useState)(!1),X=(0,a.A)($,2),ee=X[0],te=X[1],ne=(0,i.useRef)(null),re=(0,i.useRef)(null),oe=(0,i.useState)(!1),ae=(0,a.A)(oe,2),ie=ae[0],se=ae[1],le=(0,$t.gl)({id:t.id}),de=le.attributes,ce=le.listeners,ue=le.setNodeRef,me=le.transform,pe=le.transition,ge=le.isDragging,he=(0,i.useCallback)(()=>{const e=re.current;e&&se(e.scrollWidth>e.clientWidth)},[]);(0,i.useLayoutEffect)(()=>{he()},[t.name,he]),(0,i.useEffect)(()=>{const e=re.current;if(!e||"undefined"===typeof ResizeObserver)return;const t=new ResizeObserver(()=>he());return t.observe(e),()=>t.disconnect()},[he]);const fe={transform:Xt.Ks.Transform.toString(me),transition:pe,opacity:ge?0:1},ye=U||ge||W,ve=n===t.id,xe=Ot(t.documentFolders),be=ve,we=ve&&null==k;(0,i.useEffect)(()=>{var e;H&&(null===(e=ne.current)||void 0===e||e.focus())},[H]);return(0,We.jsxs)("li",{className:"list-none",children:[(0,We.jsxs)("div",{ref:ue,style:fe,onMouseEnter:()=>M(!0),onMouseLeave:()=>M(!1),onClick:()=>r(t.id),onDrop:y?e=>y(e,t.id):void 0,onDragOver:v?e=>v(e,t.id):void 0,onDragLeave:x?e=>x(e,t.id):void 0,className:"\n                flex items-center px-2 py-1 rounded cursor-pointer text-sm transition-[background-color,color,border-color] duration-200 group\n                ".concat(we?"bg-blue-100 text-blue-700":ve?"bg-blue-50 text-blue-700":"text-gray-700 hover:bg-gray-100","\n                ").concat(f===t.id?"border-2 border-blue-500 bg-blue-50 shadow-lg transform scale-105 text-blue-700":"border-2 border-transparent","\n            "),children:[(0,We.jsx)("div",(0,o.A)((0,o.A)((0,o.A)({},de),ce),{},{className:"mr-2 cursor-grab active:cursor-grabbing text-gray-400 hover:text-gray-600 transition-opacity duration-200 flex-shrink-0 ".concat(ye?"opacity-100":"opacity-0"),onClick:e=>e.stopPropagation(),children:(0,We.jsx)(Tt.A,{className:"h-4 w-4",style:{width:"1rem",he
1ight:"1rem",flexShrink:0}})})),(0,We.jsx)("button",{onClick:e=>{e.stopPropagation(),b(t)},className:"mr-2 flex-shrink-0 hover:bg-gray-200 rounded p-0.5 transition-colors duration-200",title:"Change emoji",children:t.emoji?(0,We.jsx)("span",{className:"text-base",style:{width:"1rem",height:"1rem",display:"inline-block",lineHeight:"1rem"},children:t.emoji}):(0,We.jsx)(g.A,{className:"transition-colors duration-200 ".concat(f===t.id?"text-blue-600":""),style:{width:"1rem",height:"1rem"}})}),(0,We.jsxs)("span",{ref:re,title:ie&&t.name?t.name:void 0,className:"flex-grow truncate font-medium transition-colors duration-200 ".concat(f===t.id?"text-blue-700":""),children:[t.name,t.isExternalWorkspace&&(0,We.jsx)("span",{className:"ml-1.5 text-[10px] font-semibold uppercase tracking-wide text-blue-700 bg-blue-50 px-1.5 py-0.5 rounded align-middle",children:"Shared"})]}),h&&(0,We.jsx)(l.A,{className:"text-blue-500 mr-2 flex-shrink-0",style:{width:"1rem",height:"1rem"},title:"This workspace is being shared publicly"}),p>0&&(0,We.jsx)("span",{className:"inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 text-xs font-bold leading-none text-white bg-red-500 rounded-full mr-2 flex-shrink-0",children:p}),(0,We.jsx)(pn,{workspace:t,isArchivedView:m,onCreateWorkspace:c,onArchive:d,onDelete:s,visible:U,onOpenChange:V})]}),be&&(xe.length>0||S)&&(0,We.jsxs)("ul",{className:"mt-0.5 mb-1 ml-6 space-y-0.5 border-l border-gray-200 pl-2",children:[xe.map(e=>{const n=k===e.id,r="".concat(t.id,":").concat(e.id),o=P===r;return(0,We.jsx)("li",{children:(0,We.jsxs)("button",{type:"button",onClick:n=>{n.stopPropagation(),null===A||void 0===A||A(t.id,e.id)},onDragOver:R?n=>R(n,t.id,e.id):void 0,onDragLeave:F?n=>F(n,t.id,e.id):void 0,onDrop:I?n=>I(n,t.id,e.id):void 0,className:"w-full flex items-center gap-1.5 px-2 py-1 rounded text-sm truncate ".concat(o?"bg-brand/10 text-brand ring-1 ring-brand":n?"bg-blue-50 text-blue-700":"text-gray-500 hover:bg-gray-50 hover:text-gray-700"),title:I?"Open ".concat(e.name," (or drop a document here)"):e.name,children:[n?(0,We.jsx)(Rt.A,{className:"h-3.5 w-3.5 flex-shrink-0"}):(0,We.jsx)(g.A,{className:"h-3.5 w-3.5 flex-shrink-0 text-gray-400"}),(0,We.jsx)("span",{className:"truncate",children:e.name})]})},e.id)}),S&&!H&&(0,We.jsx)("li",{children:(0,We.jsxs)("button",{type:"button",onClick:e=>{e.stopPropagation(),G(!0)},className:"w-full flex items-center gap-1.5 px-2 py-1 rounded text-sm text-gray-400 hover:bg-gray-50 hover:text-gray-600",children:[(0,We.jsx)(N.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,We.jsx)("span",{className:"truncate",children:"New folder"})]})}),S&&H&&(0,We.jsx)("li",{children:(0,We.jsxs)("form",{className:"flex items-center gap-1 px-1",onClick:e=>e.stopPropagation(),onSubmit:async e=>{var n;null===e||void 0===e||null===(n=e.preventDefault)||void 0===n||n.call(e);const r=Y.trim();if(r&&!ee&&j){te(!0);try{await j(t.id,r),Z(""),G(!1)}catch(o){}finally{te(!1)}}},children:[(0,We.jsx)("input",{ref:ne,value:Y,onChange:e=>Z(e.target.value),placeholder:"Folder name",disabled:ee,maxLength:60,className:"w-full min-w-0 px-1.5 py-1 text-xs border border-gray-300 rounded focus:outline-none focus:ring-1 focus:ring-blue-400"}),(0,We.jsx)("button",{type:"submit",disabled:ee||!Y.trim(),className:"text-xs text-blue-600 disabled:opacity-40 flex-shrink-0",children:"Add"}),(0,We.jsx)("button",{type:"button",disabled:ee,onClick:()=>{G(!1),Z("")},className:"text-xs text-gray-400 flex-shrink-0",children:"\u2715"})]})})]})]})},hn="folder:",fn="root";function yn(e){const t=e.active,n=e.droppableContainers;if(String(t.id).startsWith(hn))return(0,Zt.fp)(e);const r=n.filter(e=>{let t=e.id;const n=String(t);return n.startsWith(hn)||n===fn}),a=(0,Zt.TT)((0,o.A)((0,o.A)({},e),{},{droppableContainers:r}));return a.length>0?a:(0,Zt.fp)(e)}const vn=e=>{let t=e.documents,r=void 0===t?[]:t,l=e.currentWorkspace,d=e.setCurrentWorkspace,c=e.setCurrentWorkspaceObject,u=e.fetchDocuments,m=e.firestore,p=e.currentUser,h=e.currentOrganizationId,f=e.organizationId,v=void 0===f?null:f,b=e.activeView,w=e.setActiveView,k=e.workspaceList,j=e.setWorkspaceList,N=e.setCurrentPage,C=e.setCurrentDoc,S=e.hasUnsavedChanges,E=e.setShowUnsavedChangesMo
1dal,I=e.setPendingNavigation,D=(e.manualSaveTriggerRef,e.setActiveTab),P=e.orgResolved,T=void 0===P||P,R=e.workspaceFetchCompleted,O=void 0!==R&&R,F=e.onFetchWorkspacesComplete,L=e.formUnreadByWorkspace,_=e.selectedDocumentFolderId,U=void 0===_?null:_,M=e.onSelectDocumentFolder,z=e.onCreateDocumentFolder;const V=(0,i.useState)([]),J=(0,a.A)(V,2),q=J[0],H=J[1];(0,i.useEffect)(()=>{Array.isArray(k)&&0!==k.length&&H(e=>{if(!e.length)return e;const t=new Map(k.map(e=>[String(e.id),e]));let n=!1;const r=e.map(e=>{var r,a;const i=t.get(String(e.id));if(!i)return e;const s=i.documentFolders,l=s===e.documentFolders,d=i.name===e.name,c=i.emoji===e.emoji;return l&&d&&c?e:(n=!0,(0,o.A)((0,o.A)({},e),{},{name:null!==(r=i.name)&&void 0!==r?r:e.name,emoji:null!==(a=i.emoji)&&void 0!==a?a:e.emoji,documentFolders:void 0!==s?s:e.documentFolders}))});return n?r:e})},[k]);const K=(0,i.useState)(!0),Q=(0,a.A)(K,2),Y=Q[0],Z=Q[1],$=(0,i.useState)(null),X=(0,a.A)($,2),ee=(X[0],X[1],(0,i.useState)(!1)),te=(0,a.A)(ee,2),ne=te[0],re=te[1],oe=(0,i.useState)(!1),ae=(0,a.A)(oe,2),ie=ae[0],se=ae[1],le=(0,i.useState)(null),de=(0,a.A)(le,2),ce=de[0],ue=de[1],me=(0,i.useState)(null),pe=(0,a.A)(me,2),ge=pe[0],he=pe[1],fe=(0,i.useState)(null),ye=(0,a.A)(fe,2),ve=ye[0],xe=ye[1],be=(0,i.useState)(null),we=(0,a.A)(be,2),ke=we[0],Ae=we[1],je=(0,i.useState)(!1),Ne=(0,a.A)(je,2),Ce=Ne[0],Se=Ne[1],Ee=(0,i.useState)(null),De=(0,a.A)(Ee,2),Te=De[0],Re=De[1],Oe=(0,i.useState)([]),Fe=(0,a.A)(Oe,2),Le=Fe[0],_e=Fe[1],Ue=(0,i.useState)([]),Me=(0,a.A)(Ue,2),ze=Me[0],Be=Me[1],Ve=(0,i.useState)([]),Je=(0,a.A)(Ve,2),qe=Je[0],He=Je[1],Ge=(0,i.useState)([]),Ke=(0,a.A)(Ge,2),Qe=Ke[0],Ye=Ke[1],Ze=(0,i.useState)(!1),$e=(0,a.A)(Ze,2),Xe=$e[0],et=$e[1],tt=(0,i.useState)(new Set),nt=(0,a.A)(tt,2),rt=(nt[0],nt[1]),ot=(0,i.useState)(null),at=(0,a.A)(ot,2),it=at[0],st=at[1],lt=(0,i.useState)(null),dt=(0,a.A)(lt,2),ct=(dt[0],dt[1]),ut=(0,i.useMemo)(()=>null!==p&&void 0!==p&&p.uid&&(h||v||(0,Pe.getSelectedOrganizationId)())||null,[h,v,null===p||void 0===p?void 0:p.uid]),mt=Wt(q,ut),pt=Vt(mt),gt=L||{},ht=Jt(mt),ft=(e=>{const t=(0,i.useState)({}),n=(0,a.A)(t,2),r=n[0],s=n[1],l=(0,i.useRef)([]);return(0,i.useEffect)(()=>{const t=e||[],n=l.current;if(t.length===n.length&&!t.some((e,t)=>e!==n[t])&&n.length>0)return;if(l.current=t,!t||0===t.length)return void s({});const r=[];return t.forEach(e=>{try{const t=(0,B.rJ)(G.db,"shareableLinks"),n=(0,B.P)(t,(0,B._M)("workspaceId","==",e),(0,B._M)("isPublic","==",!0)),a=(0,B.aQ)(n,t=>{const n=t.docs.some(e=>!e.data().documentId);s(t=>(0,o.A)((0,o.A)({},t),{},{[e]:n}))},t=>{console.error("Error with active links listener for ".concat(e,":"),t),s(t=>(0,o.A)((0,o.A)({},t),{},{[e]:!1}))});r.push(a)}catch(t){console.error("Failed to set up listener for workspace ".concat(e,":"),t)}}),()=>{r.forEach(e=>{try{e()}catch(t){console.error("Error unsubscribing:",t)}})}},[null===e||void 0===e?void 0:e.join(",")]),r})(mt),yt=(0,i.useRef)(l),vt=(0,i.useRef)(0);(0,i.useEffect)(()=>{yt.current=l},[l]);const xt=(0,Zt.FR)((0,Zt.MS)(Zt.AN),(0,Zt.MS)(Zt.uN,{coordinateGetter:$t.JR})),bt=(0,i.useCallback)(async e=>{if(null!==p&&void 0!==p&&p.uid&&ut)try{const t=(0,B.doc)(G.db,"users",p.uid);await(0,B.mZ)(t,{["".concat(on,".").concat(ut,".workspaceOrder")]:e,updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Workspace order saved to Firestore:",e)}catch(t){console.error("\u274c Error saving workspace order:",t),Ie.Ay.error("Failed to save workspace order")}},[null===p||void 0===p?void 0:p.uid,ut]),wt=(0,i.useCallback)(async(e,t)=>{if(null!==p&&void 0!==p&&p.uid&&ut)try{const n=(0,B.doc)(G.db,"users",p.uid);await(0,B.mZ)(n,{["".concat(on,".").concat(ut,".workspaceFolders")]:e,["".concat(on,".").concat(ut,".folderOrder")]:t,updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Folder data saved to Firestore")}catch(n){console.error("\u274c Error saving folder data:",n),Ie.Ay.error("Failed to save folder structure")}},[null===p||void 0===p?void 0:p.uid,ut]),kt=(0,i.useCallback)(async e=>{if(null!==p&&void 0!==p&&p.uid&&ut)try{const t=(0,B.doc)(G.db,"users",p.uid);await(0,B.mZ)(t,{["".concat(on,".").concat(ut,".archivedWorkspaceIds")]:e,updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Archived workspaces saved to Firestore:",e)}catch(t){console.error("\u274c Error saving archived workspaces:",t),Ie.Ay.error("Failed to update archived workspaces")}},[null===p||void 0===p?void 0:p.uid,ut]);(0,i.useEffect)(()=>{et(!1)},[ut]);const At=(0,i.useCallback)((e,t)=>{if(!t||!Array.isArray(t)||0===t.length)return e;const n=new Map(e.map(e=>[e.id,e])),r=t.map(e=>
1n.get(e)).filter(Boolean),o=new Set(r.map(e=>e.id)),a=[...e.filter(e=>!o.has(e.id))].sort((e,t)=>(e.name||"").localeCompare(t.name||"",void 0,{sensitivity:"base"}));return[...r,...a]},[]),jt=(0,i.useCallback)(async function(){let e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];if(null===p||void 0===p||!p.uid)return void(0,W.gg)("\u23f3 Waiting for currentUser:",{userId:null===p||void 0===p?void 0:p.uid});if(!ut)return(0,W.gg)("\u23f3 No resolved organization id; clearing workspace list"),console.info("[OrgSwitch][ProjectManager] no resolved org; clearing workspaces",{userId:p.uid,selectedOrgId:(0,Pe.getSelectedOrganizationId)()||null,currentOrganizationIdProp:h||null,organizationId:v||null,orgResolved:T}),++vt.current,H([]),_e([]),Be([]),He([]),d(null),null===c||void 0===c||c(null),j&&"function"===typeof j&&j([]),Z(!1),void("function"===typeof F&&F(null,null));const t=++vt.current,r=ut;let a;(0,W.gg)("[OrgSwitch] fetchWorkspaces START gen=".concat(t," org=").concat(r)),console.info("[OrgSwitch][ProjectManager] fetchWorkspaces start",{generation:t,userId:p.uid,resolvedOrgId:ut,selectedOrgId:(0,Pe.getSelectedOrganizationId)()||null,currentOrganizationIdProp:h||null,organizationId:v||null,activeView:b,showLoading:e,orgResolved:T});try{e&&Z(!0);const a=await Promise.resolve().then(n.bind(n,47081)),i=a.getWorkspaces,s=a.getUserOrganizationData,c=await i();console.info("[OrgSwitch][ProjectManager] getWorkspaces returned",{generation:t,orgId:r,rawWorkspaceCount:c.length});let m=c;try{const e=await s(ut);e&&(m=(0,nn.jI)(c,e.id),m=dn(m),(0,W.gg)("Filtered workspaces by organization ".concat(e.name,": ").concat(m.length," of ").concat(c.length)),console.info("[OrgSwitch][ProjectManager] workspaces filtered by org",{generation:t,requestedOrgId:ut,resolvedOrgId:e.id,role:e.role||null,rawWorkspaceCount:c.length,filteredWorkspaceCount:m.length}))}catch(l){String((null===l||void 0===l?void 0:l.message)||"").includes("User is not part of any organization")?(0,W.gg)("Skipping workspace filter by org (no organization):",(null===l||void 0===l?void 0:l.message)||l):console.error("Error filtering workspaces by organization:",l),ut&&(m=(0,nn.jI)(c,ut),m=dn(m),console.info("[OrgSwitch][ProjectManager] workspace org filter fallback applied",{generation:t,requestedOrgId:ut,filteredWorkspaceCount:m.length})),console.info("[OrgSwitch][ProjectManager] workspace org filter failed",{generation:t,requestedOrgId:ut,code:(null===l||void 0===l?void 0:l.code)||null,message:(null===l||void 0===l?void 0:l.message)||null})}(0,W.gg)("Found ".concat(m.length," accessible workspaces"));const g=(0,B.doc)(G.db,"users",p.uid),h=await(0,B.getDoc)(g);let f=h.exists()?h.data():{};if(h.exists()&&function(e){return!!e&&((!e[on]||"object"!==typeof e[on])&&(Array.isArray(e.workspaceFolders)&&e.workspaceFolders.length>0||Array.isArray(e.folderOrder)&&e.folderOrder.length>0||Array.isArray(e.workspaceOrder)&&e.workspaceOrder.length>0))}(f)){const e="org-".concat(p.uid);try{const t=an(f.workspaceFolders,f.folderOrder,f.workspaceOrder,c,e);await(0,B.mZ)(g,{[on]:t,workspaceFolders:(0,B.CL)(),folderOrder:(0,B.CL)(),workspaceOrder:(0,B.CL)(),updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Migrated workspace folder layout to per-organization storage");const n=await(0,B.getDoc)(g);f=n.exists()?n.data():{}}catch(u){console.error("\u274c Legacy layout migration failed:",u)}}if(t!==vt.current)return void(0,W.gg)("[OrgSwitch] Discarding stale fetchWorkspaces response gen=".concat(t," (current=").concat(vt.current,") org=").concat(r));const y="org-".concat(p.uid),v=ln(f,ut,c,y),x=v.workspaceFolders,w=v.folderOrder,k=v.workspaceOrder,A=v.archivedWorkspaceIds;_e(x),Be(w);const N=new Set(m.map(e=>e.id)),C=sn(A).filter(e=>N.has(e));Ye(C);const S=new Set(C),E=null!=k&&k.length>0?k:null,I=new Set((x||[]).flatMap(e=>e.workspaceIds||[])),D=E&&E.length>0?x.length>0?sn(E.filter(e=>!I.has(e))):sn(E):[];let P;He(D),E&&E.length>0?P=At(m,E):(P=[...m].sort((e,t)=>(e.name||"").localeCompare(t.name||"",void 0,{sensitivity:"base"})),P.length>0&&0===x.length&&He(P.map(e=>e.id)));let T=P;if(P.some(e=>void 0===e.documentFolders)&&(T=await Promise.all(P.map(async e=>{if(void 0!==e.documentFolders)return e;try{var t;const n=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",e.id)),r=n.exists()?null===(t=n.data())||void 0===t?void 0:t.documentFolders:void 0;return(0,o.A)((0,o.A)({},e),{},{documentFolders:Ot(Array.isArray(r)?r:[])})}catch(n){return(0,o.A)((0,o.A)({},e),{},{documentFolders:[]})}})),t!==vt.current))return;if(H(T),j&&"function"===typeof j&&(j(T),(0,W.gg)("[OrgSwitch] fetchWorkspaces APPLIED gen=".concat(t," org=").concat(r," count=").concat(T.length)),console.info("[OrgSwitch][ProjectManager] fetchWorkspaces applied",{generation:t,orgId:r,workspaceCount:T.length,workspaceIds:T.map(e=>e.id)})),P.length>0&&!yt.current&&"global"!==b){const e=P.filter(e=>!S.has(e.id)),t=e.length>0?e:P,n=(0,en.ur)(null===p||void 0===p?void 0:p.uid,ut);if(n&&t.some(e=>String(e.id)===String(n)))(0,W.gg)("\ud83d\udd27 ProjectManager: restoring last-used workspace",n),d(n);else{const e=t.find(e=>!0===e.isDefault)||t.find(e=>"Default Workspace"===e.name)||t[0];d(e.id)}}}catch(m){a=m,console.error("Error fetching workspaces:",m)}finally{var i,s;e&&Z(!1),console.info("[OrgSwitch][ProjectManager] fetchWorkspaces complete",{generation:t,orgId:r,hasError:Boolean(a),errorCode:(null===(i=a)||void 0===i?void 0:i.code)||null,errorMessage:(null===(s=a)||void 0===s?void 0:s.message)||null}),"function"===typeof F&&F(r,a)}},[null===p||void 0===p?void 0:p.uid,ut,h,v,T,d,c,j,b,At,F]);(0,i.useEffect)(()=>
1{if(null!==p&&void 0!==p&&p.uid&&!1!==T)return ut?void jt():(++vt.current,H([]),_e([]),Be([]),He([]),d(null),null===c||void 0===c||c(null),j&&"function"===typeof j&&j([]),Z(!1),void("function"===typeof F&&F(null,null)))},[null===p||void 0===p?void 0:p.uid,ut,T]),(0,i.useEffect)(()=>{const e=e=>{const t=e.detail||{},n=t.workspaceId,r=t.updates;n&&r&&((0,W.gg)("\ud83d\udd04 Received workspacePropertyUpdated event:",n,r),H(e=>e.map(e=>e.id===n?(0,o.A)((0,o.A)({},e),r):e)),j&&"function"===typeof j&&j(e=>e.map(e=>e.id===n?(0,o.A)((0,o.A)({},e),r):e)))};return window.addEventListener("workspacePropertyUpdated",e),()=>window.removeEventListener("workspacePropertyUpdated",e)},[j]),(0,i.useEffect)(()=>{const e=t=>{var n,r;(0,W.gg)("\ud83d\udd04 Received workspacesUpdated event, refreshing workspaces...");const o=!1!==(null===(n=t.detail)||void 0===n?void 0:n.needsFullRefresh);if(!(!0===(null===(r=t.detail)||void 0===r?void 0:r.skipFetch))){const t=setTimeout(()=>{jt(o)},300);e.timeoutId&&clearTimeout(e.timeoutId),e.timeoutId=t}};return window.addEventListener("workspacesUpdated",e),()=>{window.removeEventListener("workspacesUpdated",e),e.timeoutId&&clearTimeout(e.timeoutId)}},[jt]);const Nt=(0,i.useCallback)(e=>{if((0,W.gg)("\ud83d\udd04 handleSelectWorkspace called with:",e),(0,W.gg)("\ud83d\udcc4 setCurrentPage function available:",!!N),(0,W.gg)("\ud83d\udcc4 setCurrentDoc function available:",!!C),S&&E&&I)return(0,W.gg)("\u26a0\ufe0f Unsaved changes detected, showing confirmation modal"),I(()=>()=>{N&&((0,W.gg)("\ud83e\uddf9 Clearing currentPage..."),N(null)),C&&((0,W.gg)("\ud83e\uddf9 Clearing currentDoc..."),C(null)),null===D||void 0===D||D("documents"),(0,W.gg)("\ud83c\udfe2 Setting current workspace to:",e),d(e),(0,W.gg)("\ud83d\udc41\ufe0f Setting active view to: workspace"),w("workspace");const t=q.find(t=>t.id===e);t&&c&&((0,W.gg)("\ud83d\udcc1 Setting workspace object:",t.name),c(t))}),void E(!0);N?((0,W.gg)("\ud83e\uddf9 Clearing currentPage..."),N(null)):console.warn("\u274c setCurrentPage function not available!"),C?((0,W.gg)("\ud83e\uddf9 Clearing currentDoc..."),C(null)):console.warn("\u274c setCurrentDoc function not available!"),null===D||void 0===D||D("documents"),(0,W.gg)("\ud83c\udfe2 Setting current workspace to:",e),d(e),(0,W.gg)("\ud83d\udc41\ufe0f Setting active view to: workspace"),w("workspace");const t=q.find(t=>t.id===e);if(t&&c&&((0,W.gg)("\ud83d\udcc1 Setting workspace object:",t.name),c(t)),null!==p&&void 0!==p&&p.uid&&e){const n=(null===t||void 0===t?void 0:t.organizationId)||v||h||(0,Pe.getSelectedOrganizationId)()||null;(0,tn.yc)(p.uid,e,n).catch(()=>{})}null===M||void 0===M||M(e,null),(0,W.gg)("\u2705 handleSelectWorkspace completed")},[N,C,d,w,D,q,c,S,E,I,null===p||void 0===p?void 0:p.uid,v,h,M]),Ct=(0,i.useCallback)(e=>{var t,n;if(!e||null===p||void 0===p||!p.uid)return!1;const r=e.userRole||(null===(t=e.memberRoles)||void 0===t?void 0:t[p.uid])||(null===(n=e.accessRoles)||void 0===n?void 0:n[p.uid])||null;return"admin"===r||"editor"===r},[null===p||void 0===p?void 0:p.uid]),St=(0,i.useCallback)((e,t)=>{if(!e||!t)return;if(S)return I(()=>()=>{N&&N(null),C&&C(null),null===D||void 0===D||D("documents"),d(e),w("workspace");const n=q.find(t=>t.id===e);n&&c&&c(n),null===M||void 0===M||M(e,t)}),void E(!0);N&&N(null),C&&C(null),null===D||void 0===D||D("documents"),d(e),w("workspace");const n=q.find(t=>t.id===e);n&&c&&c(n),null===M||void 0===M||M(e,t)},[S,I,E,N,C,D,d,w,q,c,M]);(0,i.useEffect)(()=>{const e=e=>{const t=e.detail.workspaceId;(0,W.gg)("\ud83c\udfaf Received selectDefaultWorkspace event for:",t),Nt(t)};return(0,W.gg)("\ud83c\udfa7 Setting up selectDefaultWorkspace event listener"),window.addEventListener("selectDefaultWorkspace",e),()=>{(0,W.gg)("\ud83e\uddf9 Cleaning up selectDefaultWorkspace event listener"),window.removeEventListener("selectDefaultWorkspace",e)}},[Nt]);const Et=(e,t)=>{e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",Ae(null),xe(t)},It=(e,t)=>{e.currentTarget.contains(e.relatedTarget)||xe(null)},Dt=async(e,t)=>{e.preventDefault(),e.stopPropagation(),xe(null);const n=e.dataTransfer.getData("docId");if(n)try{const e=(0,B.doc)(m,"knowledgeBaseDocuments",n),a=await(0,B.getDoc)(e);if(!a.exists())return void console.warn("Document does not exist");if((a.data().workspaceIds||[]).includes(t)){var r;return("string"===typeof(null===(r=a.data())||void 0===r?void 0:r.folderId)?a.data().folderId.trim():"")?(await(0,B.mZ)(e,{folderId:(0,B.CL)(),updatedAt:(0,B.O5)()}
1),window.dispatchEvent(new CustomEvent("documentFolderLocalUpdate",{detail:{documentIds:[n],folderId:null}})),Ie.Ay.success("Moved to All documents"),void window.dispatchEvent(new CustomEvent("clearDocumentDragState"))):((0,W.gg)("\ud83d\udfe1 Document already belongs to workspace ".concat(t,", no action taken")),Ie.Ay.success("Document already in this workspace"),void window.dispatchEvent(new CustomEvent("clearDocumentDragState")))}await(0,B.mZ)(e,(0,o.A)((0,o.A)({workspaceIds:(0,B.hq)(t)},await rn(a.data(),t)),{},{updatedAt:(0,B.O5)()})),(0,W.gg)("\u2705 Document ".concat(n," added to workspace ").concat(t)),Ie.Ay.success("Document added to workspace"),window.dispatchEvent(new CustomEvent("clearDocumentDragState"))}catch(a){console.error("\u274c Error adding document to workspace:",a),Ie.Ay.error("Failed to add document to workspace"),window.dispatchEvent(new CustomEvent("clearDocumentDragState"))}else console.warn("No docId found in dataTransfer")},Rt=(e,t,n)=>{e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",xe(null),Ae("".concat(t,":").concat(n))},Ft=(e,t,n)=>{const r="".concat(t,":").concat(n),o=e.relatedTarget;o&&e.currentTarget.contains(o)||Ae(e=>e===r?null:e)},Lt=async(e,t,n)=>{e.preventDefault(),e.stopPropagation(),Ae(null),xe(null);const r=e.dataTransfer.getData("docId");if(r&&t&&n)try{const e=(0,B.doc)(m,"knowledgeBaseDocuments",r),o=await(0,B.getDoc)(e);if(!o.exists())return Ie.Ay.error("Document not found"),void window.dispatchEvent(new CustomEvent("clearDocumentDragState"));const a=o.data()||{},i=a.workspaceIds||[],s={folderId:String(n),updatedAt:(0,B.O5)()};i.includes(t)||(s.workspaceIds=(0,B.hq)(t),Object.assign(s,await rn(a,t))),await(0,B.mZ)(e,s),window.dispatchEvent(new CustomEvent("documentFolderLocalUpdate",{detail:{documentIds:[r],folderId:String(n)}})),Ie.Ay.success("Moved to folder"),window.dispatchEvent(new CustomEvent("clearDocumentDragState"))}catch(o){console.error("\u274c Error moving document to folder:",o),Ie.Ay.error("Failed to move document to folder"),window.dispatchEvent(new CustomEvent("clearDocumentDragState"))}},_t=((0,i.useCallback)(async e=>{let t=e.name;const n=e.workspaceIds||[],r="folder_".concat(Date.now(),"_").concat(Math.random().toString(36).slice(2,9)),a={id:r,name:t,workspaceIds:[...n]};_e(e=>{const t=[...e.map(e=>(0,o.A)((0,o.A)({},e),{},{workspaceIds:(e.workspaceIds||[]).filter(e=>!n.includes(e))})),a];return wt(t,[...ze,r]),t}),Be(e=>[...e,r]),rt(e=>new Set([...e,r])),n.length>0&&He(e=>{const t=e.filter(e=>!n.includes(e));return bt(t),t}),Ie.Ay.success("Workspace group created"),(0,W.gg)("\u2705 Workspace group created:",r,t)},[Le,ze,wt,bt]),(e,t)=>{e.stopPropagation(),ue(t),he(null),se(!0)}),Ut=(0,i.useCallback)((e,t)=>{if(!e)return;const n=t?Qe.filter(t=>t!==e):sn([...Qe,e]);if(Ye(n),kt(n),t)Ie.Ay.success("Workspace restored to sidebar"),0===n.length&&et(!1);else if(Ie.Ay.success("Workspace archived for you"),l===e){const t=q.find(t=>t.id!==e&&!n.includes(t.id));t?Nt(t.id):(d(null),"function"===typeof u&&u(null))}},[Qe,kt,l,q,Nt,d,u]),Mt=(0,i.useCallback)(()=>{if(!ce)return;const e=ce.id;H(t=>{const n=t.filter(t=>t.id!==e);return j&&"function"===typeof j&&(j(n),(0,W.gg)("\ud83d\udd04 Updated parent workspaceList after deleting project:",n.length,"workspaces")),n}),He(t=>{const n=t.filter(t=>t!==e);return bt(n),n}),Ye(t=>{if(!t.includes(e))return t;const n=t.filter(t=>t!==e);return kt(n),n}),_e(t=>{const n=t.map(t=>(0,o.A)((0,o.A)({},t),{},{workspaceIds:(t.workspaceIds||[]).filter(t=>t!==e)}));return wt(n,ze),n}),l===e&&(d(null),"function"===typeof u&&u(null)),se(!1),ue(null),he(null),window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!1,skipFetch:!0}}))},[ce,l,j,u,ze,bt,wt,kt,d]),zt=(0,i.useCallback)(e=>{for(const t of Le)if((t.workspaceIds||[]).includes(e))return{type:"folder",folderId:t.id};return qe.includes(e)?{type:"root"}:null},[Le,qe]),qt=((0,i.useCallback)((e,t)=>{const n=zt(e);n&&(_e(n=>{const r=n.map(n=>{const r=(n.workspaceIds||[]).filter(t=>t!==e);return n.id!==t||r.includes(e)||r.push(e),(0,o.A)((0,o.A)({},n),{},{workspaceIds:r})});return wt(r,ze),r}),"root"===n.type&&He(t=>{const n=t.filter(t=>t!==e);return bt(n),n}))},[zt,ze,bt,wt]),(0,i.useCallback)((e,t)=>{const n=zt(e);n&&"root"!==n.type&&(_e(t=>{const n=t.map(t=>(0,o.A)((0,o.A)({},t),{},{workspaceIds:(t.workspaceIds||[]).filter(t=>t!==e)}));return wt(n,ze),n}),He(n=>{const r=[...n];return r.splice(t,0,e),bt(r),r}))}
1,[zt,ze,wt,bt]),(0,i.useCallback)((e,t)=>{_e(n=>{const r=n.map(n=>n.id===e?(0,o.A)((0,o.A)({},n),{},{name:t}):n);return wt(r,ze),r}),Ie.Ay.success("Folder renamed")},[ze,wt]),(0,i.useCallback)((e,t)=>{e.stopPropagation(),ct(t)},[]),(0,i.useCallback)(e=>{if(!e)return;const t=(e.workspaceIds||[]).filter(e=>q.some(t=>t.id===e)),n=Le.filter(t=>t.id!==e.id),r=ze.filter(t=>t!==e.id),o=[...t,...qe];_e(n),Be(r),He(o),wt(n,r),bt(o),ct(null),Ie.Ay.success("Folder deleted")},[ze,Le,qe,wt,bt,q]),(0,i.useMemo)(()=>{const e=new Set(q.map(e=>e.id)),t=new Set,n=[],r=r=>{r&&!t.has(r)&&e.has(r)&&(t.add(r),n.push(r))};for(const o of qe)r(o);for(const o of ze){const e=Le.find(e=>e.id===o);for(const t of(null===e||void 0===e?void 0:e.workspaceIds)||[])r(t)}for(const o of Le)for(const e of(null===o||void 0===o?void 0:o.workspaceIds)||[])r(e);for(const o of q)r(o.id);return n},[q,qe,Le,ze])),Ht=(0,i.useMemo)(()=>new Set(Qe),[Qe]),Gt=(0,i.useMemo)(()=>qt.filter(e=>!Ht.has(e)),[qt,Ht]),Kt=(0,i.useMemo)(()=>qt.filter(e=>Ht.has(e)),[qt,Ht]),Qt=Y||Boolean(null===p||void 0===p?void 0:p.uid)&&!0!==(null===p||void 0===p?void 0:p.isAnonymous)&&0===q.length&&(!T||!O),Xt=Gt,cn=(0,i.useRef)(!1);(0,i.useEffect)(()=>{if(cn.current)return;if(!ut||null===p||void 0===p||!p.uid||Y)return;if(!Le.length)return;cn.current=!0;const e=qt;_e([]),Be([]),He(e),rt(new Set),wt([],[]),bt(e),(0,W.gg)("\ud83d\udcc1 Flattened legacy workspace groups; workspaces are top-level")},[ut,null===p||void 0===p?void 0:p.uid,Y,Le,qt,wt,bt]);const vn=e=>{Re(e),Se(!0)};return(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"workspace-container mb-4",children:[(0,We.jsxs)("h3",{className:"text-xs font-semibold text-gray-400 uppercase tracking-wider px-2 mb-2 flex justify-between items-center",children:[(0,We.jsx)("span",{children:"Workspaces"}),(0,We.jsx)("button",{type:"button",onClick:()=>re(!0),className:"project-list text-xs text-blue-500 hover:text-blue-700 flex-shrink-0",title:"Create workspace",children:(0,We.jsx)(x.A,{className:"h-4 w-4",style:{width:"1rem",he
1ight:"1rem",flexShrink:0}})})]}),Qt?(0,We.jsxs)("div",{role:"status","aria-busy":"true",className:"px-2",children:[(0,We.jsx)("span",{className:"sr-only",children:"Loading workspaces"}),(0,We.jsx)("ul",{className:"space-y-1","aria-hidden":"true",children:["w-[72%]","w-[88%]","w-[64%]","w-[80%]","w-[56%]"].map((e,t)=>(0,We.jsxs)("li",{className:"flex items-center py-1",children:[(0,We.jsx)("div",{className:"mr-2 h-4 w-4 flex-shrink-0"}),(0,We.jsx)("div",{className:"mr-2 h-4 w-4 flex-shrink-0 rounded-brand-sm bg-surface-sunken animate-pulse"}),(0,We.jsx)("div",{className:"h-3 rounded-brand-md bg-surface-sunken animate-pulse ".concat(e)})]},"workspace-skeleton-".concat(t)))})]}):0===q.length?null:(0,We.jsxs)(We.Fragment,{children:[0===Gt.length?(0,We.jsx)("p",{className:"px-2 text-xs text-gray-400 mb-1",children:"All workspaces are archived for you"}):(0,We.jsxs)(Zt.Mp,{sensors:xt,collisionDetection:yn,onDragStart:e=>st(e.active.id),onDragEnd:e=>{const t=e.active,n=e.over;if(st(null),!n)return;const r=String(n.id),o=String(t.id);if(o.startsWith(hn)||r.startsWith(hn))return;if(r===fn)return;const a=Gt.indexOf(o),i=Gt.indexOf(r);if(-1===a||-1===i||a===i)return;const l=(0,$t.be)([...Gt],a,i),d=new Set(l),c=qt.filter(e=>!d.has(e)),u=[...l,...c];(0,s.flushSync)(()=>{He(u)}),bt(u)},children:[(0,We.jsx)($t.gB,{items:Xt,strategy:$t._G,children:(0,We.jsx)("ul",{className:"space-y-1",children:Gt.map(e=>{const t=q.find(t=>t.id===e);return t?(0,We.jsx)(gn,{workspace:t,currentWorkspace:l,onSelect:Nt,onDelete:_t,onArchive:Ut,onCreateWorkspace:()=>re(!0),isArchivedView:!1,unreadCount:Bt(t,t.id,pt,gt,ht,ut),hasActiveLink:ft[t.id],dragOverWorkspace:ve,onDropDocument:Dt,onDragOverDocument:Et,onDragLeaveDocument:It,onEmojiClick:vn,selectedDocumentFolderId:U,onSelectDocumentFolder:St,onCreateDocumentFolder:z,canCreateDocumentFolder:Ct(t),onDropDocumentOnFolder:Lt,dragOverDocumentFolderKey:ke,onDragOverDocumentFolder:Rt,onDragLeaveDocumentFolder:Ft},t.id):null})})}),(0,We.jsx)(Zt.Hd,{dropAnimation:{duration:200,easing:"cubic-bezier(0.18, 0.67, 0.6, 1.22)"},children:null!=it?(()=>{const e=q.find(e=>e.id===String(it));return e?(0,We.jsxs)("div",{className:"flex items-center px-2 py-1 rounded text-sm bg-white border-2 border-blue-200 shadow-lg cursor-grabbing opacity-95 min-w-[140px]",children:[(0,We.jsx)(Tt.A,{className:"h-4 w-4 mr-2 text-gray-400 flex-shrink-0",style:{width:"1rem",he
1ight:"1rem"}}),e.emoji?(0,We.jsx)("span",{className:"mr-2 text-base flex-shrink-0",style:{width:"1rem",height:"1rem",display:"inline-block",lineHeight:"1rem"},children:e.emoji}):(0,We.jsx)(g.A,{className:"h-4 w-4 mr-2 flex-shrink-0 text-gray-500",style:{width:"1rem",height:"1rem"}}),(0,We.jsx)("span",{className:"flex-grow truncate font-medium text-gray-700",title:e.name||void 0,children:e.name})]}):null})():null})]}),Kt.length>0&&(0,We.jsxs)("div",{className:"mt-1",children:[(0,We.jsxs)("button",{type:"button",onClick:()=>et(e=>!e),className:"w-full flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors",title:Xe?"Collapse archived workspaces":"Show archived workspaces",children:[Xe?(0,We.jsx)(y.A,{className:"h-3.5 w-3.5 flex-shrink-0"}):(0,We.jsx)(A.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,We.jsx)(Pt.A,{className:"h-3.5 w-3.5 flex-shrink-0"}),(0,We.jsxs)("span",{className:"truncate",children:["Archived (",Kt.length,")"]})]}),Xe&&(0,We.jsx)("ul",{className:"mt-0.5 space-y-0.5",children:Kt.map(e=>{const t=q.find(t=>t.id===e);if(!t)return null;const n=l===t.id;return(0,We.jsx)("li",{className:"list-none",children:(0,We.jsxs)("div",{onClick:()=>Nt(t.id),className:"\n                                                            group flex items-center px-2 py-1 rounded cursor-pointer text-sm transition-colors\n                                                            ".concat(n?"bg-blue-100 text-blue-700":"text-gray-500 hover:bg-gray-100 hover:text-gray-700","\n                                                        "),children:[(0,We.jsx)("span",{className:"mr-2 flex-shrink-0 opacity-70",children:t.emoji?(0,We.jsx)("span",{className:"text-base",style:{width:"1rem",he
1ight:"1rem",display:"inline-block",lineHeight:"1rem"},children:t.emoji}):(0,We.jsx)(g.A,{className:"h-4 w-4",style:{width:"1rem",height:"1rem"}})}),(0,We.jsx)("span",{className:"flex-grow truncate font-medium",title:t.name||void 0,children:t.name}),(0,We.jsx)(pn,{workspace:t,isArchivedView:!0,onCreateWorkspace:()=>re(!0),onArchive:Ut,onDelete:_t})]})},t.id)})})]})]})]}),(0,We.jsx)(un,{isOpen:ne,onClose:()=>re(!1),onSubmitWorkspace:async e=>{if(null===p||void 0===p||!p.uid)return console.error("Cannot create project: missing currentUser"),void Ie.Ay.error("Unable to create workspace. Please refresh the page.");const t=await Promise.resolve().then(n.bind(n,47081)),r=t.getSelectedOrganizationId,o=t.getUserOrganizationData,a=r()||v;if(!a)return console.error("Cannot create project: missing organizationId"),void Ie.Ay.error("Unable to create workspace. Please select an organization.");try{(0,W.gg)("\ud83d\udd12 Checking organization permissions before workspace creation...",{selectedOrgId:a,organizationId:v});const e=await o(a);if(!e)return(0,W.gg)("\u274c No organization data found"),void Ie.Ay.error("Unable to verify organization permissions. Please refresh the page.");if((0,W.gg)("\ud83d\udccb Organization data:",{orgId:e.id,orgName:e.name,userRole:e.role,isEditor:e.isEditor,isAdmin:e.isAdmin}),"viewer"===e.role)return(0,W.gg)("\ud83d\udeab BLOCKED: User is a viewer, cannot create workspaces"),void Ie.Ay.error("Your viewer permissions don't allow creation of new workspaces. Only editors and admins can create workspaces.");if(!e.isEditor&&!e.isAdmin)return(0,W.gg)("\ud83d\udeab BLOCKED: User is not an editor or admin",{role:e.role,isEditor:e.isEditor,isAdmin:e.isAdmin}),void("viewer"===e.role?Ie.Ay.error("Your viewer permissions don't allow creation of new workspaces. Only editors and admins can create workspaces."):Ie.Ay.error("You do not have permission to create workspaces. Only editors and admins can create workspaces."));(0,W.gg)("\u2705 Permission check passed - user can create workspaces")}catch(s){return console.error("\u274c Error checking organization permissions:",s),(0,W.gg)("\u274c Error checking organization permissions:",s),void Ie.Ay.error("Unable to verify organization permissions. Please refresh the page.")}let i=0;for(;i<3;)try{(0,W.gg)("\ud83d\udd04 Attempt ".concat(i+1,"/").concat(3," to create workspace")),await p.getIdToken(!0),(0,W.gg)("\u2705 Auth token refreshed");const t={name:e,organizationId:a,createdAt:new Date,visibility:"organization",memberRoles:{[p.uid]:"admin"},usageStats:{documentsCount:0,storageUsed:0},ownerEmail:p.email};await new Promise(e=>setTimeout(e,500));const n=await(0,B.gS)((0,B.rJ)(m,"workspaces"),t);(0,W.gg)("\u2705 Workspace created successfully:",n.id);const r={id:n.id,name:e,organizationId:a,createdAt:t.createdAt,visibility:t.visibility,memberRoles:t.memberRoles,usageStats:t.usageStats,ownerEmail:t.ownerEmail,userRole:"admin",documentsCount:0,storageUsed:0,description:"",emoji:null};return(0,W.gg)("\ud83d\udd0d Adding workspace to local state:",{workspaceOrgId:r.organizationId,selectedOrgId:a,organizationId:v,match:r.organizationId===a}),r.organizationId===a||r.organizationId===v?H(e=>{const t=[r,...e];return j&&"function"===typeof j&&j(t),t}):((0,W.gg)("\u26a0\ufe0f Organization ID mismatch - workspace orgId:",r.organizationId,"vs selected orgId:",a),H(e=>{if(!e.some(e=>e.id===r.id)){const t=[r,...e];return(0,W.gg)("\u2705 Added workspace despite org mismatch (workspace was just created):",t.length,"workspaces"),j&&"function"===typeof j&&j(t),t}return e})),He(e=>[n.id,...e]),bt([n.id,...qe]).catch(e=>{console.error("Error saving workspace order:",e)}),void window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!1,skipFetch:!0}}))}catch(l){console.error("\u274c Creation attempt ".concat(i+1," failed:"),l),i++,i>=3?(console.error("\u274c All creation attempts failed"),alert("Failed to create workspace after multiple attempts. Please try again or refresh the page.")):await new Promise(e=>setTimeout(e,1e3*i))}}}),(0,We.jsx)(mn,{isOpen:ie,projectToDelete:ce,documents:r,workspaces:q,activeLinks:ft,moveTargetWorkspaceId:ge,setMoveTargetWorkspaceId:he,onConfirmDelete:async()=>{var e;if(ce)if("admin"===(null===(e=ce.memberRoles)||void 0===e?void 0:e[p.uid])){(0,W.gg)("Attempting to delete project:",{id:ce.id,name:ce.name,organizationId:ce.organizationId});try{const e=(0,B.doc)(m,"workspaces",ce.id);if(!(await(0,B.getDoc)(e)).exists())return(0,W.gg)("Document does not exist, it may have been already deleted"),H(e=>e.filter(e=>e.id!==ce.id)),j&&"function"===typeof j&&j(e=>e.filter(e=>e.id!==ce.id)),se(!1),ue(null),void he(null);await(0,B.kd)(e),(0,W.gg)("Project deleted successfully from Firestore"),Mt()}catch(t){console.error("Error deleting workspace:",t),"permission-denied"===t.code?Ie.Ay.error("You do not have permission to delete this project."):"not-found"===t.code?((0,Ie.Ay)("Project not found. It may have already been deleted.",{icon:"\u26a0\ufe0f"}),H(e=>e.filter(e=>e.id!==ce.id)),j&&"function"===typeof j&&j(e=>e.filter(e=>e.id!==ce.id))):Ie.Ay.error("Failed to delete project: ".concat(t.message)),se(!1),ue(null),he(null)}}else Ie.Ay.error("You do not have permission to delete this project.");
1else console.error("No project selected for deletion")},onConfirmMoveAndDelete:async e=>{var t;if(!ce||!e)return;if("admin"!==(null===(t=ce.memberRoles)||void 0===t?void 0:t[p.uid]))return void Ie.Ay.error("You do not have permission to delete this project.");const n=ce.id,o=(r||[]).filter(e=>(e.workspaceIds||[]).some(e=>String(e)===String(n))),a=o.filter(e=>!0!==e.locked),i=o.filter(e=>!0===e.locked);try{var s;for(const o of a){const t=(0,B.doc)(m,"knowledgeBaseDocuments",o.id),r=(o.workspaceIds||[]).map(e=>String(e)).filter(e=>e!==String(n)),a=r.includes(String(e))?r:[...r,e];await(0,B.mZ)(t,{workspaceIds:a,updatedAt:(0,B.O5)()})}const t=(null===(s=q.find(t=>String(t.id)===String(e)))||void 0===s?void 0:s.name)||e;if(a.length>0&&Ie.Ay.success("Moved ".concat(a.length," document").concat(1!==a.length?"s":""," to ").concat(t)),i.length>0){const e=i.map(e=>e.title||e.fileName||"Untitled").join(", ");(0,Ie.Ay)("".concat(i.length," locked document").concat(1!==i.length?"s":""," were not moved: ").concat(e,". Unlock and move manually if needed."),{icon:"\u26a0\ufe0f",duration:6e3})}const r=(0,B.doc)(m,"workspaces",ce.id);(await(0,B.getDoc)(r)).exists()&&(await(0,B.kd)(r),(0,W.gg)("Project deleted successfully from Firestore after move")),Mt()}catch(l){console.error("Error moving documents or deleting workspace:",l),Ie.Ay.error((null===l||void 0===l?void 0:l.message)||"Failed to move documents or delete workspace")}},onCancel:()=>{se(!1),ue(null),he(null)}}),(0,We.jsx)(Yt,{isOpen:Ce,onClose:()=>{Se(!1),Re(null)},onSelect:async e=>{if(Te)try{const t=(0,B.doc)(m,"workspaces",Te.id);await(0,B.mZ)(t,{emoji:e,updatedAt:(0,B.O5)()}),H(t=>t.map(t=>t.id===Te.id?(0,o.A)((0,o.A)({},t),{},{emoji:e}):t)),j&&"function"===typeof j&&j(t=>t.map(t=>t.id===Te.id?(0,o.A)((0,o.A)({},t),{},{emoji:e}):t)),Ie.Ay.success("Emoji updated!"),(0,W.gg)("\u2705 Emoji saved for workspace:",Te.id,e),window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!1,skipFetch:!0}}))}catch(t){console.error("\u274c Error saving emoji:",t),Ie.Ay.error("Failed to save emoji")}finally{Se(!1),Re(null)}},currentEmoji:(null===Te||void 0===Te?void 0:Te.emoji)||null})]})},xn=()=>(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 hover:shadow-md transition-all duration-200 group relative select-none cursor-move animate-pulse",children:[(0,We.jsx)("div",{className:"w-full h-32 bg-gray-200 rounded-t-lg"}),(0,We.jsxs)("div",{className:"p-4",children:[(0,We.jsx)("div",{className:"h-4 bg-gray-200 rounded w-3/4 mb-2"}),(0,We.jsx)("div",{className:"h-3 bg-gray-200 rounded w-1/3"})]})]}),bn=e=>{let t=e.isLoading,n=e.isGlobalView,r=e.canEdit;return t?(0,We.jsx)("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mt-4",children:Array.from({length:6}).map((e,t)=>(0,We.jsx)(xn,{},"skeleton-".concat(t)))}):(0,We.jsxs)("div",{className:"text-center py-10",children:[(0,We.jsx)(R.A,{className:"h-10 w-10 text-gray-300 mx-auto mb-4","aria-hidden":"true"}),(0,We.jsx)("p",{className:"text-gray-500",children:n?"No accessible documents":"No documents in this workspace"}),(0,We.jsx)("p",{className:"text-gray-400 text-sm mt-1",children:r?"Add documents to start building your knowledge base":"Contact an admin or editor to add documents"})]})},wn=xn;var kn=n(7104),An=n(30441);const jn=(e,t)=>{const n=(0,i.useState)(!1),r=(0,a.A)(n,2),o=r[0],s=r[1],l=(0,i.useState)(null),d=(0,a.A)(l,2),c=d[0],u=d[1],m=(0,i.useState)(null),p=(0,a.A)(m,2),g=p[0],h=p[1],f=t&&Array.isArray(t)?t.sort().join(","):"";return(0,i.useEffect)(()=>{if(!e||!t||0===t.length)return s(!1),u(null),void h(null);(async()=>{try{const o=(0,B.doc)(G.db,"knowledgeBaseDocuments",e);let l;try{l=await(0,B.getDoc)(o)}catch(a){var t;if("permission-denied"===a.code||null!==(t=a.message)&&void 0!==t&&t.includes("Missing or insufficient permissions"))return s(!1),u(null),void h(null);throw a}if(l.exists()){const e=l.data();if(e.shareableLinkId){var n;const t=(0,B.doc)(G.db,"shareableLinks",e.shareableLinkId);let o;try{o=await(0,B.getDoc)(t)}catch(i){var r;if(!("permission-denied"===i.code||null!==(r=i.message)&&void 0!==r&&r.includes("Missing or insufficient permissions")))throw i}if(null!==(n=o)&&void 0!==n&&n.exists()){const e=o.data();if(e.isPublic){if(!e.expiryDate)return s(!0),void u("document");
1if((e.expiryDate.toDate?e.expiryDate.toDate():new Date(e.expiryDate))>new Date)return s(!0),void u("document")}}}}s(!1),u(null),h(null)}catch(l){var o;"permission-denied"===l.code||null!==(o=l.message)&&void 0!==o&&o.includes("Missing or insufficient permissions")||console.error("Error checking live status:",l),s(!1),u(null),h(null)}})()},[e,f]),{isLive:o,liveSource:c,liveWorkspaceId:g}};var Nn=n(60678),Cn=n(82054),Sn=n(698);function En(e){const t=function(e){const t=(0,i.useState)(null),n=(0,a.A)(t,2),r=n[0],o=n[1];return(0,i.useEffect)(()=>{if(!e)return void o(null);let t=!1;return(async()=>{try{const n=(await(0,Sn.mf)(e)).filter(e=>"pending_signature"===e.status||"completed"===e.status);if(0===n.length)return void(t||o(null));const r=n.slice().sort((e,t)=>{const n=e=>{var t,n,r,o,a,i;return null!==(t=null!==(n=null===(r=e.createdAt)||void 0===r||null===(o=r.toMillis)||void 0===o?void 0:o.call(r))&&void 0!==n?n:null===(a=e.updatedAt)||void 0===a||null===(i=a.toMillis)||void 0===i?void 0:i.call(a))&&void 0!==t?t:"number"===typeof e.createdAt?e.createdAt:0};return n(t)-n(e)})[0];t||o("completed"===r.status?"completed":"pending_signature")}catch(n){t||o(null)}})(),()=>{t=!0}},[e]),r}(e.documentId);return t?"completed"===t?(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700",title:"All parties have signed",children:[(0,We.jsx)(Cn.A,{className:"w-3 h-3 shrink-0"}),"Signed"]}):"pending_signature"===t?(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700",title:"Waiting for all signers to complete",children:[(0,We.jsx)(lt.A,{className:"w-3 h-3 shrink-0"}),"Awaiting Signature"]}):null:null}var In=n(94659),Dn=n(23524);const Pn=e=>{let t=e.isVisible,n=e.videoUrl,r=e.title,o=e.onClose,a=e.talkId;if(!t)return null;const i=a?"".concat(window.location.origin,"/shared/video/").concat(a,"?docTitle=").concat(encodeURIComponent(r||"AI Generated Video")):n;return(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50 p-4",onClick:o,children:(0,We.jsxs)("div",{className:"bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,We.jsxs)("div",{className:"flex justify-between items-center p-4 border-b",children:[(0,We.jsx)("h3",{className:"text-lg font-semibold",children:"AI Generated Video"}),(0,We.jsx)("button",{onClick:o,className:"text-gray-400 hover:text-gray-600 transition-colors",children:(0,We.jsx)(c.A,{className:"w-6 h-6"})})]}),(0,We.jsxs)("div",{className:"p-4",children:[(0,We.jsxs)("video",{controls:!0,autoPlay:!0,className:"w-full rounded",style:{maxHeight:"70vh"},children:[(0,We.jsx)("source",{src:n,type:"video/mp4"}),"Your browser does not support the video tag."]}),(0,We.jsxs)("div",{className:"mt-4 flex items-center justify-between",children:[(0,We.jsx)("p",{className:"text-sm text-gray-600",children:r||"Document Summary"}),(0,We.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,We.jsxs)("button",{onClick:()=>{const e=document.createElement("a");e.href=n,e.download="ai-video.mp4",e.click()},className:"px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm transition-colors flex items-center gap-2",children:[(0,We.jsx)(kn.A,{className:"w-4 h-4"}),"Download"]}),(0,We.jsxs)("button",{onClick:async()=>{if(navigator.share)try{await navigator.share({title:"AI Generated Video",url:n})}catch(e){(0,W.gg)("Share failed:",e)}else try{await navigator.clipboard.writeText(n),alert("Video URL copied to clipboard!")}catch(e){(0,W.gg)("Copy failed:",e)}},className:"px-4 py-2 bg-green-500 hover:bg-green-600 text-white rounded text-sm transition-colors flex items-center gap-2",children:[(0,We.jsx)(An.A,{className:"w-4 h-4"}),"Share"]})]})]}),(0,We.jsxs)("div",{className:"mt-2 text-sm text-gray-600 break-all",children:[(0,We.jsx)("span",{children:"Shareable link: "}),(0,We.jsx)("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:underline break-all",children:i})]})]})]})})},Tn=e=>{var t,n,r,s,d,c;let u=e.doc,m=e.canEdit,h=e.isGlobalView,f=e.workspaceData,y=e.currentWorkspace,v=e.deleteDocument,x=e.removeDocumentFromWorkspace,k=e.getKnowledgeBaseDocuments,A=e.setKnowledgeBase,j=e.minimal,N=void 0!==j&&j,C=e.navigate,S=e.workspaceList,E=e.documentSignaturesEnabled,I=void 0!==E&&E,D=e.documentLockEnabled,P=void 0!==D&&D,T=e.onDuplicate,R=e.organizationId,O=e.onFetchCategory,F=e.fetchingCategoryDocIds,L=void 0===F?new Set:F;(0,W.gg)("DocumentCardWithVideoLoader rendered with doc:",u),(0,W.gg)("Document ID:",null===u||void 0===u?void 0:u.id),(0,W.gg)("Document category:",null===u||void 0===u?void 0:u.category);const _=(0,i.useState)(!1),U=(0,a.A)(_,2),M=U[0],z=U[1],B=(0,i.useState)(0),V=(0,a.A)(B,2),J=V[0],q=V[1],G=(0,i.useState)(""),K=(0,a.A)(G,2),Q=K[0],Y=K[1],Z=(0,i.useState)(!1),$=(0,a.A)(Z,2),X=$[0],ee=$[1],te=(0,i.useState)(""),ne=(0,a.A)(te,2),re=ne[0],ie=ne[1],se=(0,i.useState)(null),le=(0,a.A)(se,2),de=le[0],ce=le[1],ue=(0,i.useState)(null),me=(0,a.A)(ue,2),pe=me[0],ge=me[1],he=(0,i.useState)(""),fe=(0,a.A)(he,2),ye=(fe[0],fe[1],(0,i.use
1State)(!1)),ve=(0,a.A)(ye,2),xe=(ve[0],ve[1],(0,i.useState)(!1)),be=(0,a.A)(xe,2),we=be[0],ke=be[1],Ae=(0,i.useState)(null),je=(0,a.A)(Ae,2),Ne=je[0],Ce=je[1],Ee=(0,i.useState)(""),De=(0,a.A)(Ee,2),Pe=De[0],Te=De[1],Re=(0,i.useState)(null),Oe=(0,a.A)(Re,2),Fe=Oe[0],Le=Oe[1],Ue=(0,i.useState)(!1),Me=(0,a.A)(Ue,2),ze=Me[0],Be=Me[1],Ve=(0,i.useState)(!1),Je=(0,a.A)(Ve,2),qe=Je[0],He=Je[1],Ge=(null===u||void 0===u?void 0:u.workspaceIds)||[],Ke=jn(null===u||void 0===u?void 0:u.id,Ge),Qe=Ke.isLive,Ye=Ke.liveSource,Ze=Ke.liveWorkspaceId,$e=(e,t)=>{Y(e),q(t)},Xe=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const n=Math.min(30+4*t,90),r=["Processing audio...","Generating avatar...","Syncing movements...","Rendering video...","Almost ready..."],o=Math.min(Math.floor(t/4),r.length-1);$e(r[o],n);try{const n=await fetch("".concat("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/getTalkStatus","?id=").concat(e));if(!n.ok)throw new Error("Failed to check status");const r=await n.json();if("done"===r.status)$e("Complete!",100),setTimeout(()=>{z(!1),ie(r.result_url),ee(!0)},500);else if("error"===r.status)z(!1),alert("Video generation failed. Please try again.");else{const n=setTimeout(()=>Xe(e,t+1),3e3);ce(n)}}catch(a){z(!1),alert("Error checking video status.")}},et=(0,i.useMemo)(()=>{const e=(0,_e.Od)(u,"Untitled Document");return(0,W.gg)("Document card display title:",e),e},[u]),tt=(0,i.useMemo)(()=>(0,Nn.AD)(u),[u]),nt=(0,i.useMemo)(()=>u.workspaceIds&&Array.isArray(u.workspaceIds)&&S?u.workspaceIds.filter(e=>null!==e&&void 0!==e).map(e=>{const t=S.find(t=>t.id===e);return t?t.name:null}).filter(e=>null!==e):[],[u.workspaceIds,S]),rt=(0,i.useMemo)(()=>{var e;const t=(null===f||void 0===f?void 0:f.documentFolders)||(y&&S?null===(e=S.find(e=>e.id===y))||void 0===e?void 0:e.documentFolders:null);return Lt(u,t)},[u,null===f||void 0===f?void 0:f.documentFolders,S,y]);if(N)return m?(0,We.jsxs)("div",{className:"inline-flex items-center space-x-2",children:[(0,We.jsx)("button",{onClick:e=>{e.stopPropagation(),M?(de&&(clearTimeout(de),ce(null)),z(!1),q(0),Y("")):(async e=>{const t=e.summary||et||"Here is your document summary.";z(!0),$e("Starting...",10);const n={presenter_id:"amy-jBaWBW8MSc",script:{type:"text",input:t,provider:{type:"microsoft",voice_id:"en-US-JennyNeural",voice_config:{style:"Cheerful"}}},config:{stitch:!0}};try{$e("Sending request...",20);const e=await fetch("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/createAvatarTalk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!e.ok){const t=await e.json();throw new Error(t.error||"Failed to create video")}const t=await e.json();if(!t.id)throw new Error("No video ID returned");ge(t.id),$e("Processing...",30),Xe(t.id)}catch(r){z(!1),alert("Failed to generate video: ".concat(r.message))}})(u)},disabled:M,className:"inline-flex items-center px-2 py-1 text-xs font-medium rounded transition-all ".concat(M?"text-orange-600 bg-orange-50":"text-blue-600 hover:bg-blue-50"),title:M?"Cancel video generation":"Create talking head video",children:M?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Se.y$,{size:"sm",className:"mr-1"}),(0,We.jsx)("span",{children:"Cancel"})]}):(0,We.jsx)(We.Fragment,{children:(0,We.jsx)("span",{children:"\ud83c\udfa5"})})}),M&&(0,We.jsxs)("div",{className:"inline-flex items-center space-x-1",children:[(0,We.jsx)("span",{className:"text-xs text-gray-600",children:Q}),(0,We.jsxs)("span",{className:"text-xs text-gray-500",children:[J,"%"]})]}),(0,We.jsx)(Pn,{isVisible:X,videoUrl:re,title:et,onClose:()=>ee(!1),talkId:pe})]}):null;const ot=(null===Ne||void 0===Ne||null===(t=Ne.doc)||void 0===t?void 0:t.locked)&&!(null!==Ne&&void 0!==Ne&&Ne.isGlobalView),at=(null===Ne||void 0===Ne||null===(n=Ne.doc)||void 0===n?void 0:n.locked)&&(null===Ne||void 0===Ne?void 0:Ne.isGlobalView),it=(0,ae.Nn)(null===Ne||void 0===Ne?void 0:Ne.doc,{isGlobalView:!(null===Ne||void 0===Ne||!Ne.isGlobalView)}),st="envVault"===it.kind;return(0,We.jsxs)("div",{className:"relative",children:[(0,We.jsxs)("div",{className:"p-4",children:[(0,We.jsxs)("div",{className:"flex justify-between items-center",children:[(0,We.jsx)("h3",{className:"text-sm font-medium text-gray-900 truncate pointer-events-none",children:et}),m&&(0,We.jsxs)("div",{className:"flex items-center space-x-2",children:[T&&(0,We.jsx)("button",{onClick:async e=>{if(e.stopPropagation(),T&&null!==u&&void 0!==u&&u.id){He(!0);try{await T(u.id),(0,W.gg)("\u2705 Document duplicated successfully")}catch(t){console.error("\u274c Error duplicating document:",t),alert("Failed to duplicate document. Please try again.")}finally{He(!1)}}else(0,W.gg)("\u274c Cannot duplicate: missing onDuplicate handler or doc.id")},onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"data-action":"duplicate",disabled:qe,className:"p-1 text-gray-400 hover:text-blue-500 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-auto disabled:opacity-50",title:"Duplicate document",children:qe?(0,We.jsx)(Se.y$,{size:"sm"}):(0,We.jsx)(w.A,{className:"h-4 w-4"})}),(0,We.jsx)("button",{onClick:e=>{if(e.stopPropagation(),(0,W.gg)("\ud83d\ude80 Delete operation initiated"),(0,W.gg)("\ud83d\udcc4 Document to delete:",{id:u.id,title:et}),!u||!u.id||!Array.isArray(u.workspaceIds))return void console.warn("\u2757 Invalid document passed to delete handler:",u);const t={doc:u,computedTitle:et,isGlobalView:h,currentWorkspace:y,workspaceData:f};(0,W.gg)("\ud83d\udccb Storing document data:",t),Te(""),Le(null),Ce(t),ke(!0),(0,W.gg)("\ud83d\udd13 Modal should be opening now")},onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"data-action":"delete",className:"p-1 text-gray-400 hover:text-red-500 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-auto",title:"Delete document",children:(0,We.jsx)(p.A,{className:"h-4 w-4"})})]})]}),(0,We.jsxs)("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[("Uncategorized"===(u.category||"Uncategorized")||"General"===u.category)&&m&&O?(0,We.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),e.preventDefault(),O(u)},disabled:L.has(u.id),className:"text-xs text-gray-500 hover:text-gray-700 hover:underline focus:outline-none focus:ring-0 disabled:opacity-50 pointer-events-auto",title:"Fetch category",children:L.has(u.id)?"\u2026":u.category||"Uncategorized"}):(0,We.jsx)("p",{className:"text-xs text-gray-500 pointer-events-none",children:u.category||"Uncategorized"}),Qe&&(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700",title:"document"===Ye?"This document has its own public link. It was shared individually, not through the workspace.":"workspace"===Ye?null!==S&&void 0!==S&&S.length&&Ze?"Shared publicly via ".concat(null!==(r=null===(s=S.find(e=>e.id===Ze))||void 0===s?void 0:s.name)&&void 0!==r?r:Ze):"Shared publicly via this workspace.":void 0,children:[(0,We.jsx)(l.A,{className:"w-3 h-3"}),"Live"]}),!0===(null===u||void 0===u?void 0:u.isTemplate)&&(0,We.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800 pointer-events-none",title:"Used as a fillable template",children:"Template"}),I&&(0,We.jsx)(En,{documentId:null===u||void 0===u?void 0:u.id}),P&&(null===u||void 0===u?void 0:u.locked)&&(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700 pointer-events-none",children:[(0,We.jsx)(b.A,{className:"w-3 h-3"}),"Locked"]}),Array.isArray(null===u||void 0===u?void 0:u.workspaceIds)&&u.workspaceIds.length>0&&(null===u||void 0===u?void 0:u.workspaceSearchIndexStatus)&&(0,We.jsx)(In.A,{status:u.workspaceSearchIndexStatus,error:u.workspaceSearchIndexError}),(rt||nt.length>0)&&(0,We.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap",children:[rt&&(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700 border border-gray-200 pointer-events-none",children:[(0,We.jsx)(g.A,{className:"h-3 w-3"}),rt]}),nt.map((e,t)=>(0,We.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700 pointer-events-none",children:e},t))]})]}),tt.visibleText&&(0,We.jsx)("p",{className:"text-xs text-gray-400 mt-1 pointer-events-none",title:tt.title||void 0,children:tt.visibleText}),M&&(0,We.jsxs)("div",{className:"mt-3 space-y-2",children:[(0,We.jsxs)("div",{className:"flex justify-between items-center",children:[(0,We.jsx)("span",{className:"text-xs text-gray-600",children:Q}),(0,We.jsxs)("span",{className:"text-xs text-gray-500",children:[J,"%"]})]}),(0,We.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-1.5",children:(0,We.jsx)("div",{className:"bg-blue-500 h-1.5 rounded-full transition-all duration-500",style:{width:"".concat(J,"%")}})}),(0,We.jsx)("p",{className:"text-xs text-gray-400",children:"Usually takes 1-3 minutes"})]})]}),(0,We.jsx)(Pn,{isVisible:X,videoUrl:re,title:et,onClose:()=>ee(!1),talkId:pe}),(0,We.jsx)(Dn.R,{isOpen:we,title:ot?"Unlock document":null!==Ne&&void 0!==Ne&&Ne.isGlobalView?"Delete Document":"Remove Document",message:ot?'Type "unlock document" below to unlock this document. Then you can remove it from the "'.concat(null===Ne||void 0===Ne||null===(d=Ne.workspaceData)||void 0===d?void 0:d.name,'" workspace.'):null!==Ne&&void 0!==Ne&&Ne.isGlobalView?at?'This document is locked. Type "unlock document" below, then click "Unlock and delete" to permanently delete "'.concat(null===Ne||void 0===Ne?void 0:Ne.computedTitle,'".'):st?'This secrets document cannot be deleted accidentally. Type "'.concat(ae.ZE,'" below, then click Delete to permanently delete "').concat(null===Ne||void 0===Ne?void 0:Ne.computedTitle,'".'):'Are you sure you want to permanently delete "'.concat(null===Ne||void 0===Ne?void 0:Ne.computedTitle,'"?'):'Remove "'.concat(null===Ne||void 0===Ne?void 0:Ne.computedTitle,'" from the "').concat(null===Ne||void 0===Ne||null===(c=Ne.workspaceData)||void 0===c?void 0:c.name,'" workspace?'),onConfirm:ot?async()=>
1{if(null===Ne||void 0===Ne||!Ne.doc||null!==Ne&&void 0!==Ne&&Ne.isGlobalView||!R)return;const e=Ne.doc;Le(null),Be(!0);try{await(0,H.w5)(e.id,R,Pe),A(t=>null!==t&&void 0!==t&&t.documents?(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>t.id===e.id?(0,o.A)((0,o.A)({},t),{},{locked:!1}):t)}):t),Ce(e=>e?(0,o.A)((0,o.A)({},e),{},{doc:(0,o.A)((0,o.A)({},e.doc),{},{locked:!1})}):e),Te(""),Le(null)}catch(t){const e=(null===t||void 0===t?void 0:t.message)||"Failed to unlock document.";(0,ae.LD)(e)?Le(e):Ie.Ay.error(e)}finally{Be(!1)}}:async()=>{if((0,W.gg)("\ud83c\udfaf handleConfirmDelete called!"),(0,W.gg)("\ud83d\udccb documentToDelete state:",Ne),!Ne)return void console.error("\u274c No document data available for deletion");const e=Ne.doc,t=Ne.isGlobalView,n=Ne.currentWorkspace;if(t||null===e||void 0===e||!e.locked){Le(null),Be(!0);try{(0,W.gg)("\u2705 User confirmed delete");let r=!1;if(t){const t=(0,ae.Gp)(e,Pe,{isGlobalView:!0});await v(e.id,t),r=!0}else{const t=await x(e.id,n);if(null!==t&&void 0!==t&&t.shouldDelete){if((0,oe.z7)(e))return Ie.Ay.error('To permanently delete this secrets document, use All documents and type "'.concat(ae.ZE,'".')),ke(!1),Ce(null),Te(""),void Le(null);await v(e.id),r=!0}}if((0,W.gg)("\ud83d\udd04 Executing delete action..."),(0,W.gg)("\u2705 Delete action completed successfully"),(0,W.gg)("\ud83d\udd04 Refreshing knowledge base..."),t){const e=await k(C,S);A(e)}else A(t=>(0,o.A)((0,o.A)({},t),{},{documents:((null===t||void 0===t?void 0:t.documents)||[]).filter(t=>t.id!==e.id)}));(0,W.gg)("\u2705 Knowledge base state updated"),Ie.Ay.success(r?"Document deleted successfully":"Document removed from workspace"),ke(!1),Ce(null),Te(""),Le(null)}catch(r){console.error("\u274c Error during delete operation:",r);const e=(null===r||void 0===r?void 0:r.message)||"Failed to delete document. Please try again.";(0,ae.LD)(e)?Le(e):(Ie.Ay.error(e),ke(!1),Ce(null),Te(""))}finally{Be(!1)}}},onCancel:()=>{ke(!1),Ce(null),Te(""),Le(null)},confirmText:ot?"Unlock":null!==Ne&&void 0!==Ne&&Ne.isGlobalView?at?"Unlock and delete":"Delete":"Remove",showUnlockPhraseInput:it.showInput,unlockPhrase:Pe,onUnlockPhraseChange:Te,unlockPhraseError:Fe,unlockPhraseLabel:it.label,unlockPhrasePlaceholder:it.placeholder,requiredPhrase:it.requiredPhrase,isConfirming:ze})]})};var Rn=n(10629),On=n(76996),Fn=n(1457),Ln=n(74195),_n=n(7899),Un=n(29940),Mn=n(43866),zn=n(73002);const Bn=e=>{let t=e.doc,n=e.className,r=void 0===n?"h-12 w-12":n;const o=(e=>{e.fileName||e.title;const t=e.fileType||"",n=e.source||e.captureSource||"",r=e.category||"";if(n.includes("chrome")||n.includes("extension")||"voice"===r||e.isVoiceCapture)return{icon:Rn.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Voice Capture"};switch(t){case"text/plain":return{icon:On.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Text Note"};case"application/pdf":return{icon:R.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"PDF"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":case"application/msword":return{icon:R.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Word Document"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":case"application/vnd.ms-excel":case"text/csv":return{icon:Fn.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Spreadsheet"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":case"application/vnd.ms-powerpoint":return{icon:Ln.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Presentation"};case"audio/mpeg":case"audio/wav":case"audio/ogg":case"audio/mp4":case"audio/aac":case"audio/webm":return{icon:_n.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Audio"};case"video/mp4":case"video/avi":case"video/mov":case"video/wmv":case"video/webm":return{icon:Un.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Video"};case"image/jpeg":case"image/png":case"image/gif":case"image/webp":case"image/svg+xml":return{icon:Mn.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Image"};case"application/json":return{icon:R.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"JSON"};default:return t.startsWith("text/")?{icon:On.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Text File"}:t.startsWith("audio/")?{icon:_n.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Audio"}:t.startsWith("video/")?{icon:Un.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Video"}:t.startsWith("image/")?{icon:Mn.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Image"}:t.startsWith("application/")?{icon:zn.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"Document"}:{icon:zn.A,color:"text-gray-500",bgColor:"bg-gray-50",label:"File"}}})(t),a=o.icon;return(0,We.jsx)("div",{className:"flex items-center justify-center ".concat(o.bgColor," rounded-lg p-3 ").concat(r.includes("h-")?"":"h-full w-full"),children:(0,We.jsx)(a,{className:"".concat(r," ").concat(o.color)})})};var Wn=n(61962),Vn=n(33945),Jn=n(97976);const qn=[e=>
1/^\s*This document is generated with the support of integrated tools\b/i.test(e),e=>/^\s*This document (?:was|has been) generated\b/i.test(e)&&/\b(integrated tools|AI[- ]generated|artificial intelligence)\b/i.test(e),e=>/^\s*This document is generated\b/i.test(e)&&/\bintegrated tools\b/i.test(e)&&/\b(enhanced efficiency|professionalism)\b/i.test(e)];function Hn(e){if(!e||"string"!==typeof e)return e;const t=e.replace(/\r\n/g,"\n").split(/\n{2,}/);for(;t.length>0;){const e=t[t.length-1].trim();if(!e){t.pop();continue}if(!qn.some(t=>t(e)))break;t.pop()}return t.join("\n\n").trimEnd()}var Gn=n(28044),Kn=n(20387),Qn=n(86836),Yn=n(81452),Zn=n(13407);const $n=new Set(["text","textarea","email","phone","number","date","url","select","radio","checkbox","image","pdf"]);function Xn(e){return e?"text"===e.type?e.text||"":Array.isArray(e.content)?e.content.map(Xn).join(""):"":""}function er(e){return e&&"heading"===e.type?Xn(e).trim():""}function tr(e){return e?"paragraph"===e.type||"heading"===e.type?Xn(e).trim():"listItem"===e.type&&Array.isArray(e.content)?e.content.map(tr).filter(Boolean).join(" ").trim():"bulletList"===e.type||"orderedList"===e.type?(e.content||[]).map(tr).filter(Boolean).join(" "):"":""}function nr(e){const t=String(e||"").trim(),n=t.toLowerCase();return/\b(email|e-mail)\b/.test(n)?"email":/\b(phone|mobile|tel)\b/.test(n)?"phone":/\b(date|deadline|when)\b/.test(n)&&!/\b(update|candidate)\b/.test(n)?"date":/\b(url|website|link|http)\b/.test(n)?"url":/\b(number|amount|quantity|count|how many)\b/.test(n)?"number":/\b(upload|attach|provide|submit|send)\b/.test(n)&&/\b(pdf|document|scan)\b/.test(n)||/\b(pdf|w-?9|1099)\b/.test(n)&&/\b(card|document|file|scan|insurance|upload)\b/.test(n)?"pdf":/\b(photos?|pictures?|screenshots?|images?)\b/.test(n)||/\b(before-and-after|business logo)\b/.test(n)||/\blogo\b/.test(n)&&/\b(resolution|upload|file|version|highest)\b/.test(n)?"image":/\b(describe|explain|details|requirements|scope|comments|notes)\b/.test(n)||t.length>120?"textarea":/^(yes|no)\s*\/\s*(yes|no)/i.test(t)||/\byes\s+or\s+no\b/i.test(n)?"radio":"text"}function rr(e){return/\b(photo|picture|visual content|visuals|images?|gallery|media)\b/i.test(String(e||""))}const or=new Set(["email","phone","url","date","number","select","radio","checkbox"]);function ar(e,t){if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;const n=function(e){return Qn.jg.test(String(e||""))&&/\b(image|photo|picture)\b/i.test(String(e||""))}(t),r=function(e){return Qn.jg.test(String(e||""))&&/\bpdf\b/i.test(String(e||""))}(t);if(!n&&!r)return e;const a=e=>{var t,i;if(!e||"object"!==typeof e)return e;if("formBlock"===e.type&&null!==(t=e.attrs)&&void 0!==t&&t.fields){let t;try{t="string"===typeof e.attrs.fields?JSON.parse(e.attrs.fields):e.attrs.fields}catch(s){return e}if(!Array.isArray(t)||!t.length)return e;const a=n&&rr(e.attrs.title),l=r&&(i=e.attrs.title,/\b(pdf|document upload|documents|paperwork|files to upload)\b/i.test(String(i||""))),d=t.map(e=>{if(!e||or.has(e.type))return e;const t=nr(e.label);return n&&(a||"image"===t)?(0,o.A)((0,o.A)({},e),{},{type:"image"}):r&&(l||"pdf"===t)?(0,o.A)((0,o.A)({},e),{},{type:"pdf"}):e});return(0,o.A)((0,o.A)({},e),{},{attrs:(0,o.A)((0,o.A)({},e.attrs),{},{fields:JSON.stringify(d)})})}return Array.isArray(e.content)?(0,o.A)((0,o.A)({},e),{},{content:e.content.map(a)}):e};return(0,o.A)((0,o.A)({},e),{},{content:e.content.map(a)})}const ir=/\b(forms?|survey|feedback|intake|questionnaire|r\.?s\.?v\.?p|registration|application)\b/i;function sr(e){return ir.test(String(e||""))}function lr(e){const t=String(e||"").replace(/\*\*/g,"").replace(/\*/g,"").trim();if(!t)return null;let n=t,r=nr(t);const o=t.match(/^(.{1,80}?):\s*(.*)$/);if(o&&o[1].length<50){const e=o[1].trim(),t=(o[2]||"").trim();if(!t||/^[_\s\u2026\.-]+$/.test(t))return n=e,r=nr(e),{label:n,type:r}}return t.endsWith("?")?(n=t.replace(/\?+\s*$/,"").trim(),r=nr(n),n?{label:n,type:r}:null):/^(name|email|phone|company|address|website)\b/i.test(t)&&t.length<80?{label:t,type:nr(t)}:null}function dr(e){const t=String(e||"").replace(/\*\*/g,"").replace(/\*/g,"").trim();if(!t)return null;if(t.length>120)return null;if(/^[A-Z][^.?!]{40,}[.!]$/.test(t))return null;if(/\b(please|complete|fill\s+out|use\s+this|the\s+following|below)\b/i.test(t)&&t.length>60)return null;const n=lr(t);return n||(t.length<=80&&!/[.!]$/.test(t)?{label:t,type:nr(t)}:null)}function cr(e){const t=$n.has(e.type)?e.type:"text",n={id:(0,Kn.J)(),type:t,label:e.label.slice(0,240),placeholder:"",required:!1,options:[]};return"radio"===t&&/\byes\s+or\s+no\b/i.test(e.label)&&(n.options=["Yes","No"]),n}function ur(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return{type:"formBlock",attrs:{formId:(0,Kn.F)(),title:(e||"Untitled Form").slice(0,240),description:(n||"").slice(0,500),fields:JSON.stringify(t),responseCount:0}}}function mr(e){return!!e&&("formBlock"===e.type||!!Array.isArray(e.content)&&e.content.some(mr))}function pr(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:new Set;return e?("formBlock"===e.type&&null!==(t=e.attrs)&&void 0!==t&&t.formId&&n.add(e.attrs.formId),Array.isArray(e.content)&&e.content.forEach(e
1=>pr(e,n)),n):n}function gr(e,t,n){const r=function(e,t,n){const r=sr(n),o=[],a=new Set(e);for(const s of e){if("bulletList"===s.type||"orderedList"===s.type)continue;const e=tr(s),t=r?dr(e):lr(e);t&&o.push(cr(t))}let i=[];for(const s of t){const e=(0,Zn.YW)(s);if(e.length)if(r){for(const t of e){const e=dr(t);e&&o.push(cr(e))}a.add(s)}else i.push(...e)}if(!r){i=[...new Set(i.map(e=>e.trim()).filter(Boolean))];const e=o.some(e=>"checkbox"===e.type&&(0,Zn.Ze)(e.options).length>0);if(i.length&&!e&&o.length){o.unshift({id:(0,Kn.J)(),type:"checkbox",label:"Select all that apply",placeholder:"",required:!1,options:i.map(e=>e.slice(0,240))});for(const e of t)(0,Zn.YW)(e).length&&a.add(e)}}if(r)for(const s of t){if(a.has(s))continue;if("paragraph"!==s.type)continue;const e=dr(tr(s));e&&(o.push(cr(e)),a.add(s))}return{fields:o,blocksToReplace:[...a]}}(n,(arguments.length>3&&void 0!==arguments[3]?arguments[3]:null)||n,t),o=r.fields,a=r.blocksToReplace;if(!o.length)return e;const i=ur(t||"Form",o),s=new Set(a),l=[];let d=!1;for(const c of e)s.has(c)?d||(l.push(i),d=!0):l.push(c);return d||l.push(i),l}function hr(e,t){return!(!e||"formBlock"===e.type)&&(sr(t)?"bulletList"===e.type||"orderedList"===e.type?(0,Zn.YW)(e).some(e=>!!dr(e)):!!dr(tr(e)):!!lr(tr(e)))}function fr(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;const n=t.userPrompt,r=void 0===n?"":n,a=t.integrationContext,i=void 0===a?null:a,s=t.formsEnabled,l=void 0!==s&&s;if(!(0,Qn.S0)(i,r,l))return e;if(mr(e)&&!Qn.AA.test(String(r||""))&&!Qn.jg.test(String(r||""))&&!function(e){if(!Array.isArray(e))return!1;let t="",n=!1,r=!1,o=!1;const a=()=>{sr(t)&&!n&&r&&(o=!0)};for(const l of e){var i,s;"heading"!==l.type||2!==(null===(i=l.attrs)||void 0===i?void 0:i.level)&&3!==(null===(s=l.attrs)||void 0===s?void 0:s.level)?"formBlock"!==l.type?hr(l,t)&&(r=!0):n=!0:(a(),t=er(l),n=!1,r=!1)}return a(),o}(e.content))return e;const d=function(e){if(!Array.isArray(e)||!e.length)return e;if(!e.some(e=>{var t,n;return"heading"===e.type&&(2===(null===(t=e.attrs)||void 0===t?void 0:t.level)||3===(null===(n=e.attrs)||void 0===n?void 0:n.level))})){const t=e.filter(e=>"formBlock"!==e.type&&!!lr(tr(e)));return t.length?e.some(e=>"formBlock"===e.type)?e:gr(e,"Form",t):e}const t=[];let n="",r=[],o=[];const a=()=>{o.length&&!r.some(e=>"formBlock"===e.type)?t.push(...gr(r,n,o,r)):t.push(...r),r=[],o=[]};for(const l of e){var i,s;"heading"!==l.type||2!==(null===(i=l.attrs)||void 0===i?void 0:i.level)&&3!==(null===(s=l.attrs)||void 0===s?void 0:s.level)?"formBlock"!==l.type?(r.push(l),hr(l,n)&&o.push(l)):(a(),t.push(l)):(a(),n=er(l),t.push(l))}return a(),t}(e.content);return(0,o.A)((0,o.A)({},e),{},{content:d})}function yr(e,t){if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;if(!t||"doc"!==t.type||!Array.isArray(t.content))return e;const n=[],r=e=>{for(const t of e)"formBlock"===t.type&&n.push(t),Array.isArray(t.content)&&r(t.content)};if(r(t.content),!n.length)return e;const a=pr(e),i=n.filter(e=>{var t;return(null===(t=e.attrs)||void 0===t?void 0:t.formId)&&!a.has(e.attrs.formId)});return i.length?(0,o.A)((0,o.A)({},e),{},{content:[...e.content,...i]}):e}function vr(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return{id:(0,Kn.J)(),type:e.fieldType,label:e.label,placeholder:"",required:t,options:e.options}}function xr(e,t){if(!t.length)return e;let n=[];try{var r,a;n="string"===typeof(null===(r=e.attrs)||void 0===r?void 0:r.fields)?JSON.parse(e.attrs.fields):(null===(a=e.attrs)||void 0===a?void 0:a.fields)||[]}catch(i){n=[]}return(0,o.A)((0,o.A)({},e),{},{attrs:(0,o.A)((0,o.A)({},e.attrs),{},{fields:JSON.stringify([...n,...t])})})}function br(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=t.userPrompt,r=void 0===n?"":n,a=t.integrationContext,i=void 0===a?null:a,s=t.formsEnabled,l=void 0!==s&&s,d=t.priorTipTapJson,c=void 0===d?null:d,u=function(e){let t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;const n=[];let r=[],a="Untitled Form";const i=()=>{r.length&&(n.push(ur(a,r)),r=[],a="Untitled Form")};for(const o of e.content)if("heading"!==o.type){if("paragraph"===o.type){const e=Xn(o).trim(),n=(0,Yn.KC)(e);if(n){r.push(vr(n,t));continue}}
1"formBlock"!==o.type?(i(),n.push(o)):r.length?(n.push(xr(o,r)),r=[]):n.push(o)}else i(),a=er(o)||a,n.push(o);return i(),(0,o.A)((0,o.A)({},e),{},{content:n})}(e,Qn.HK.test(String(r||"")));let m;if((0,Qn.S0)(i,r,l)){const e=fr(u,{userPrompt:r,integrationContext:i,formsEnabled:l});m=ar((0,Zn.Us)(e),r)}else{const e=function(e){if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;const t=e=>Array.isArray(e)?e.filter(e=>"formBlock"!==(null===e||void 0===e?void 0:e.type)).map(e=>Array.isArray(null===e||void 0===e?void 0:e.content)?(0,o.A)((0,o.A)({},e),{},{content:t(e.content)}):e):e;return(0,o.A)((0,o.A)({},e),{},{content:t(e.content)})}(u),t=yr(e,c);m=ar((0,Zn.Us)(t),r)}return m=function(e,t){if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;if((0,Qn.cN)(t))return e;const n=e=>{if(!Array.isArray(e))return e;const t=[];for(const a of e){var r;"formBlock"===(null===a||void 0===a?void 0:a.type)&&rr(null===(r=a.attrs)||void 0===r?void 0:r.title)||(Array.isArray(null===a||void 0===a?void 0:a.content)?t.push((0,o.A)((0,o.A)({},a),{},{content:n(a.content)})):t.push(a))}return t};return(0,o.A)((0,o.A)({},e),{},{content:n(e.content)})}(m,r),function(e,t){return Qn.HK.test(String(t||""))&&e&&"doc"===e.type&&Array.isArray(e.content)?(0,o.A)((0,o.A)({},e),{},{content:e.content.map(e=>{var t;if(!e||"formBlock"!==e.type||null===(t=e.attrs)||void 0===t||!t.fields)return e;let n;try{n="string"===typeof e.attrs.fields?JSON.parse(e.attrs.fields):e.attrs.fields}catch(a){return e}if(!Array.isArray(n))return e;const r=n.map(e=>(0,o.A)((0,o.A)({},e),{},{required:!0}));return(0,o.A)((0,o.A)({},e),{},{attrs:(0,o.A)((0,o.A)({},e.attrs),{},{fields:JSON.stringify(r)})})})}):e}(m,r)}var wr=n(31238);const kr=/https?:\/\/(?:www\.)?stripe\.com(?:\/pay)?/i,Ar=/\$\s*([\d,]+(?:\.\d{2})?)|\b([\d,]+(?:\.\d{2})?)\s*dollars?\b/i;function jr(e){return e?"text"===e.type?e.text||"":Array.isArray(e.content)?e.content.map(jr).join(""):"":""}function Nr(e,t){e&&"object"===typeof e&&(t(e),Array.isArray(e.content)&&e.content.forEach(e=>Nr(e,t)))}function Cr(e){let t=!1;return Nr(e,e=>{"paymentButton"===e.type&&(t=!0)}),t}function Sr(e){return kr.test(String(e||""))}function Er(e){if(!(!(arguments.length>1&&void 0!==arguments[1])||arguments[1])||!e||"doc"!==e.type||!Array.isArray(e.content))return e;const t=e.content.map(e=>"paragraph"!==e.type?e:function(e){if(!e||"paragraph"!==e.type||!Array.isArray(e.content))return e;const t=[];for(const r of e.content){var n;if("text"!==r.type||!Array.isArray(r.marks)){t.push(r);continue}const e=r.marks.find(e=>"link"===e.type);e&&Sr(null===(n=e.attrs)||void 0===n?void 0:n.href)||t.push(r)}return t.length&&t.map(jr).join("").trim()?(0,o.A)((0,o.A)({},e),{},{content:t}):null}(e)).filter(Boolean);return(0,o.A)((0,o.A)({},e),{},{content:t})}function Ir(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=n.userPrompt,a=void 0===r?"":r,i=n.integrationContext,s=void 0===i?null:i,l=n.documentTitle,d=void 0===l?"":l;if(!(!0===(null===s||void 0===s||null===(t=s.enabled)||void 0===t?void 0:t.stripe))||!e||"doc"!==e.type)return{editorJson:e,paymentConfig:null};let c=Er(e,!0);if(!Cr(c)){const e=function(e){const t=String(e||"").match(Ar);if(!t)return null;const n=(t[1]||t[2]||"").replace(/,/g,""),r=parseFloat(n);return!Number.isFinite(r)||r<.5?null:Math.round(100*r)}(a);e&&(c=(0,o.A)((0,o.A)({},c),{},{content:[...c.content||[],(u=e,{type:"paymentButton",attrs:{label:m||(0,Yn.yP)(u),amountCents:null!=u&&u>0?Math.round(u):null}})]}))}var u,m;if(!Cr(c))return{editorJson:c,paymentConfig:null};const p=(d||"").trim().slice(0,200)||"Payment",g=(0,wr.S)(c,{defaultProductName:p});c=g.editorJson;const h=(g.paymentLinks||[]).filter(e=>null!=e.amountCents&&e.amountCents>=50);return h.length?{editorJson:c,paymentConfig:{paymentEnabled:!0,paymentLinks:h,paymentAmountCents:h[0].amountCents,paymentProductName:h[0].productName||p}}:{editorJson:c,paymentConfig:null}}var Dr=n(17412),Pr=n(78337),Tr=n(2859),Rr=n(39599);const Or=(0,ge.getFunctions)(),Fr=e=>{let t=e.currentUser,n=e.knowledgeBase,r=e.workspaceList,s=void 0===r?[]:r,l=e.deriveKeyFromCredential,d=e.decryptText,c=e.selectedOrganizationId,u=e.totalDocumentCount;const m=(0,i.useState)("explorer"),p=(0,a.A)(m,2),g=p[0],h=p[1],f=(0,i.useState)(!0),y=(0,a.A)(f,2),v=y[0],x=y[1],b=(0,i.useState)(null),w=(0,a.A)(b,2),k=(w[0],w[1]);(0,i.useEffect)(()=>{const e=async()=>
1{if(null!==t&&void 0!==t&&t.signupPlan)try{const e=await l(t.uid);if(e){const n=await d(t.signupPlan,e);if(n){const e=n.toLowerCase().trim();h("explorer"),(0,W.gg)("\ud83d\udd13 Using fallback signup plan:",e)}}}catch(e){console.warn("Failed to decrypt signup plan:",e),h("explorer")}else h("explorer")};(async()=>{if(null===t||void 0===t||!t.uid)return h("explorer"),void x(!1);x(!0);try{const r=(0,Pe.getSelectedOrganizationId)()||c;(0,W.gg)("[UserPlanFooter] Fetching subscription:",{userId:t.uid,selectedOrganizationId:c,localStorageOrgId:(0,Pe.getSelectedOrganizationId)(),effectiveOrgId:r});const a=(0,ge.httpsCallable)(Or,"getUserSubscription"),i=await a((0,o.A)({userId:t.uid},r?{organizationId:r}:{}));if((0,W.gg)("[UserPlanFooter] getUserSubscription response:",i.data),i.data.subscription&&i.data.subscription.plan){var n;const e=i.data.subscription.plan.toLowerCase(),t=null===(n=i.data.subscription.status)||void 0===n?void 0:n.toLowerCase();(0,W.gg)("\ud83d\udcca Plan check:",{plan:e,status:t,isPro:"pro"===e||"enterprise"===e,isActive:"active"===t||"trialing"===t}),"pro"!==e&&"enterprise"!==e||"active"!==t&&"trialing"!==t?(h("explorer"),k(i.data.subscription),(0,W.gg)("\u26a0\ufe0f Inactive subscription, using explorer plan. Plan:",e,"Status:",t)):(h(e),k(i.data.subscription),(0,W.gg)("\u2705 Active subscription found:",e,"Status:",t))}else(0,W.gg)("\u26a0\ufe0f No subscription data in response"),await e()}catch(r){console.warn("Failed to fetch subscription, falling back to signup plan:",r),await e()}finally{x(!1)}})()},[null===t||void 0===t?void 0:t.uid,null===t||void 0===t?void 0:t.signupPlan,c,l,d]);const A=null!==u&&void 0!==u?u:(()=>{if(null===n||void 0===n||!n.documents||0===n.documents.length)return(0,W.gg)("\ud83d\udcca Document counter: No documents in knowledgeBase"),0;if(!s||0===s.length)return(0,W.gg)("\ud83d\udcca Document counter: No workspaces available"),0;const e=s.map(e=>String(e.id));(0,W.gg)("\ud83d\udcca Document counter - Accessible workspace IDs:",e),(0,W.gg)("\ud83d\udcca Document counter - Total documents in knowledgeBase:",n.documents.length);const t=n.documents.filter(t=>{if(!Array.isArray(t.workspaceIds)||0===t.workspaceIds.length)return(0,W.gg)('\ud83d\udcca Document counter - Filtered out "'.concat(t.title||t.fileName,'": No valid workspaceIds array')),!1;const n=t.workspaceIds.some(t=>e.includes(String(t)));return n||(0,W.gg)('\ud83d\udcca Document counter - Filtered out "'.concat(t.title||t.fileName,'": Not in accessible workspace. workspaceIds:'),t.workspaceIds),n}),r=Array.from(new Map(t.map(e=>[e.id,e])).values());return(0,W.gg)("\ud83d\udcca Document counter - Valid documents count (after deduplication):",r.length),r.length})(),j=A>=10;return"pro"===g||"enterprise"===g?null:v?(0,We.jsx)("div",{className:"px-4 py-4 border-t border-gray-200 bg-gray-50",children:(0,We.jsxs)("div",{className:"space-y-3 animate-pulse",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsx)("div",{className:"h-4 bg-gray-200 rounded w-16"}),(0,We.jsx)("div",{className:"h-4 bg-gray-200 rounded w-8"})]}),(0,We.jsx)("div",{className:"h-2 bg-gray-200 rounded"}),(0,We.jsx)("div",{className:"h-8 bg-gray-200 rounded"})]})}):(0,We.jsxs)("div",{className:"px-4 py-4 border-t border-gray-200 bg-gray-50 space-y-3",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between text-sm",children:[(0,We.jsx)("span",{className:"text-gray-600",children:"Documents"}),(0,We.jsxs)("div",{className:"flex items-center space-x-1",children:[(0,We.jsx)("span",{className:"font-medium ".concat(j?"text-red-600":"text-gray-900"),children:A}),(0,We.jsx)("span",{className:"text-gray-400",children:"/"}),(0,We.jsx)("span",{className:"text-gray-500",children:10})]})]}),(0,We.jsx)("div",{className:"w-full bg-gray-200 rounded-full h-2",children:(0,We.jsx)("div",{className:"h-2 rounded-full transition-all duration-300 ".concat(j?"bg-red-500":A>=9?"bg-yellow-500":"bg-green-500"),style:{width:"".concat(Math.min(A/10*100,100),"%")}})}),(0,We.jsxs)("div",{className:"space-y-2",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between text-xs",children:[(0,We.jsx)("span",{className:"text-gray-500",children:"Explorer Plan"}),(0,We.jsx)("span",{className:"px-2 py-1 rounded-full text-xs font-medium ".concat(j?"bg-red-100 text-red-700":"bg-green-100 text-green-700"),children:j?"Limit Reached":"".concat(10-A," left")})]}),j?(0,We.jsx)(St.A,{type:"button",fullWidth:!0,size:"sm",onClick:()=>{(0,W.gg)("Upgrade clicked for user:",null===t||void 0===t?void 0:t.uid),window.open("/billing","_blank")},className:"w-full px-3 py-2 text-sm rounded-md transition-colors duration-200 shadow-sm",children:"Upgrade Now"}):(0,We.jsx)("button",{type:"button",onClick:()=>{(0,W.gg)("Upgrade clicked for user:",null===t||void 0===t?void 0:t.uid),window.open("/billing","_blank")},className:"w-full px-3 py-2 text-sm font-medium rounded-md transition-colors duration-200 bg-white border border-gray-300 text-gray-700 hover:bg-gray-50",children:"Upgrade to Pro"})]}),j&&(0,We.jsx)("div",{className:"bg-red-50 border border-red-200 rounded-md p-3",children:(0,We.jsxs)("div",{className:"flex items-start",children:[(0,We.jsx)("div",{className:"flex-shrink-0",children:(0,We.jsx)("svg",{className:"h-4 w-4 text-red-400 mt-0.5",fill:"currentColor",viewBox:"0 0 20 20",children:(0,We.jsx)("path",{fillRule:"evenodd",d:"M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z",clipRule:"evenodd"})})}),(0,We.jsxs)("div",{className:"ml-2",children:[(0,We.jsx)("p",{className:"text-xs text-red-700 font-medium",children:"Document limit reached"}),(0,We.jsx)("p",{className:"text-xs text-red-600 mt-1",children:"Upgrade to add unlimited documents"})]})]})})]})};let Lr={},_r=[],Ur="",Mr=0;const zr=new Map;let Br=null,Wr=null,Vr=!1;function Jr(e){return null!==e&&void 0!==e&&e.length?[...e].map(String).sort().join(","):""}
1function qr(){zr.forEach(e=>{const t=Ut(Lr,e.ids);e.onChange(e=>_t(e,t)?e:t)})}async function Hr(){if(!_r.length)return Lr={},void qr();if(Wr)return Wr;const e=_r;return Wr=(async()=>{try{var t;const n=(0,ge.getFunctions)(),r=(0,ge.httpsCallable)(n,"getWorkspaceUnreadFormResponseCounts"),o=await r({workspaceIds:e});let a={};if(null!==(t=o.data)&&void 0!==t&&t.success&&o.data.counts&&"object"===typeof o.data.counts){const t=o.data.counts;for(const n of e){a=Mt(a,n,Number(t[n])||0,e)}}else for(const t of e)a=Mt(a,t,0,e);Lr=a,qr()}catch(n){console.error("Error fetching unread form responses:",n)}finally{Wr=null}})(),Wr}function Gr(){"visible"===document.visibilityState&&Hr()}function Kr(){const e=function(){const e=new Set;return zr.forEach(t=>{(t.ids||[]).forEach(t=>{null!=t&&""!==t&&e.add(String(t))})}),[...e].sort()}(),t=Jr(e),n=t!==Ur;if(_r=e,Ur=t,!_r.length)return Br&&(clearInterval(Br),Br=null),Vr&&(document.removeEventListener("visibilitychange",Gr),Vr=!1),Lr={},void qr();Br||(Br=setInterval(Hr,6e4)),Vr||(document.addEventListener("visibilitychange",Gr),Vr=!0),n&&(Lr=Ut(Lr,_r),qr(),Hr())}var Qr=n(20438);function Yr(e){let t=e.docId,n=e.enabled,r=void 0===n||n,o=e.scrollContainerRef;const a=(0,i.useRef)(null),s=(0,i.useRef)(0),l=(0,i.useRef)(0),d=(0,i.useRef)(!0),c=(0,i.useRef)(!1),u=(0,i.useRef)(t||null),m=(0,i.useCallback)(()=>{const e=null===o||void 0===o?void 0:o.current;if(e){const t=e.scrollTop,n=e.scrollHeight,r=e.clientHeight;return n<=r?100:Math.round((t+r)/n*100)}const t=document.documentElement,n=window.scrollY||t.scrollTop,r=t.scrollHeight,a=window.innerHeight;return r<=a?100:Math.round((n+a)/r*100)},[o]),p=(0,i.useCallback)(async()=>{if(!r||!a.current||!u.current)return;if(c.current)return;const e=Math.floor(s.current/1e3),t=l.current;if(e<=0&&t<=0)return;const n=await(0,Qr.d)({sessionId:a.current,docId:u.current,durationSeconds:e,scrollDepthPct:t});(null!==n&&void 0!==n&&n.eventEmitted||null!==n&&void 0!==n&&n.deduped)&&(c.current=!0)},[r]);(0,i.useEffect)(()=>{u.current=t||null},[t]),(0,i.useEffect)(()=>{if(!r||!t||"string"!==typeof t||t.startsWith("new_"))return;a.current="undefined"!==typeof crypto&&crypto.randomUUID?crypto.randomUUID():"".concat(Date.now(),"-").concat(Math.random().toString(36).slice(2)),s.current=0,l.current=0,d.current=!0,c.current=!1;const e={current:null},n=()=>{d.current=!0,e.current&&clearTimeout(e.current),e.current=setTimeout(()=>{d.current=!1},6e4)},o=["mousemove","keydown","scroll","touchstart","click"];o.forEach(e=>window.addEventListener(e,n,{passive:!0})),n();let i=Date.now();const u=setInterval(()=>{const e=Date.now(),t=e-i;i=e,d.current&&"visible"===document.visibilityState&&(s.current+=t);const n=m();n>l.current&&(l.current=n)},1e3),g=setTimeout(()=>{p()},8e3),h=setInterval(()=>{p()},15e3),f=()=>{"hidden"===document.visibilityState&&p()};document.addEventListener("visibilitychange",f);const y=()=>{p()};return window.addEventListener("pagehide",y),(0,W.gg)("[InAppDocView] tracking started",{docId:t,sessionId:a.current}),()=>{o.forEach(e=>window.removeEventListener(e,n)),document.removeEventListener("visibilitychange",f),window.removeEventListener("pagehide",y),e.current&&clearTimeout(e.current),clearInterval(u),clearTimeout(g),clearInterval(h),p()}},[t,r,m,p])}var Zr=n(99264),$r=n(68400);const Xr=(e,t)=>{let n=document.getElementById(e);return n||(n=document.createElement("link"),n.id=e,n.rel=t,document.head.appendChild(n)),n},eo=(e,t)=>{document.querySelectorAll('link[rel*="icon"]:not([id^="dynamic-"])').forEach(e=>e.remove());const n=Xr("dynamic-favicon","icon");n.type=t,n.href=e;const r=Xr("dynamic-favicon-shortcut","shortcut icon");r.type=t,r.href=e;Xr("dynamic-apple-touch-icon","apple-touch-icon").href=e},to=()=>{eo("/based-logo.png","image/png");try{localStorage.removeItem("faviconEmoji")}catch(e){}},no=e=>{if(!e)return void to();const t=document.createElement("canvas");t.width=64,t.height=64;const n=t.getContext("2d");n.font='55px "Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif',n.textAlign="center",n.textBaseline="middle",n.fillText(e,32,35);!function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"image/png";if(e)if(e.startsWith("data:"))eo(e,t),(0,W.gg)("\u2705 Favicon updated with data URL");else{const n=new Image;n.onload=()=>{eo(e,t),(0,W.gg)("\u2705 Favicon updated with URL:",e)},n.onerror=()=>{console.warn("\u274c Failed to load favicon image:",e,"Using default instead"),to()},n.src=e}else to()}(t.toDataURL("image/png"),"image/png");try{localStorage.setItem("faviconEmoji",e)}catch(r){}};var ro=n(62658),oo=n(25349),ao=n(47935),io=n(84980),so=n(12764),lo=n(49247),co=n(8535);const uo=e=>{"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_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.
1js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #69 from grigerny/cursor/native-document-tables-6648\n\nNative document tables for editor and MCP agents",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_6MQChUZTeZEjuh9PAEPmwanHsu8y",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"fe8e0cad17d5c751081fbff8964f57a16f15178c",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-o7e1bdtta-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_DEBUG_INGEST&&fetch("http://127.0.0.1:7242/ingest/4219f023-8761-4166-88df-57347d3a6d41",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})};var mo=n(31963),po=n(73651);let go=0,ho=0;function fo(){return go}function yo(){return ho}function vo(e){let t=e.currentUser,n=e.currentPage,r=e.setKnowledgeBase,s=e.setCurrentDoc,l=e.currentDoc;const d=(0,i.useState)(!1),c=(0,a.A)(d,2),u=c[0],m=c[1],p=(0,i.useState)(!1),g=(0,a.A)(p,2),h=g[0],f=g[1],y=(0,i.useState)(null),v=(0,a.A)(y,2),x=v[0],b=v[1],w=(0,i.useState)(null),k=(0,a.A)(w,2),A=k[0],j=k[1],N=(0,i.useState)(null),C=(0,a.A)(N,2),S=C[0],E=C[1],I=(0,i.useRef)(!1),D=(0,i.useRef)(0),P=(0,i.useRef)(0),T=(0,i.useRef)(0),R=(0,i.useRef)(null),O=(0,i.useRef)(0);(0,i.useEffect)(()=>{u&&n||(b(null),j(null))},[u,n]),(0,i.useEffect)(()=>{null!==S&&n&&(null===l||void 0===l?void 0:l.id)===n&&!(null===l||void 0===l||!l.paymentSubscriptionEnabled)===S&&E(null)},[null===l||void 0===l?void 0:l.paymentSubscriptionEnabled,null===l||void 0===l?void 0:l.id,n,S]);const F=(0,i.useCallback)(async(e,n)=>{if(!e||null===t||void 0===t||!t.uid)return;const a=n.paymentEnabled,i=n.paymentAmountCents,l=n.paymentAmountFieldId,d=n.paymentRevealAfterSignature,c=n.paymentProductName,u=n.paymentReminderEnabled,m=n.paymentLinks,p=n.paymentSubscriptionEnabled,g=n.paymentSubscriptionAmountCents,h=n.paymentSubscriptionProductName,y=n.paymentSubscriptionInterval,v=void 0!==a;if(v&&I.current)return;const x=Date.now()-P.current;if(!1===a&&((0,po.g)("[Payment] Turn-off requested",{timeSinceTurnOn:x,willIgnore:x<1e4}),x<1e4))return void(0,po.g)("[Payment] Ignoring turn-off \u2013 turned on recently (within 10s)");if(!0===a){const e=Date.now();P.current=e,go=e}if(!0===p){const e=Date.now();T.current=e,ho=e,E(!0)}else!1===p&&E(!1);D.current=Date.now();const b=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({},void 0!==a&&{paymentEnabled:!!a}),void 0!==i&&{paymentAmountCents:null==i||""===i?null:Number(i)}),void 0!==l&&{paymentAmountFieldId:null==l||""===l?null:l}),void 0!==d&&{paymentRevealAfterSignature:!!d}),void 0!==c&&{paymentProductName:c||null}),void 0!==u&&{paymentReminderEnabled:!!u}),void 0!==m&&{paymentLinks:Array.isArray(m)?m:null}),void 0!==p&&{paymentSubscriptionEnabled:!!p}),void 0!==g&&{paymentSubscriptionAmountCents:null==g||""===g?null:Number(g)}),void 0!==h&&{paymentSubscriptionProductName:h||null}),void 0!==y&&{paymentSubscriptionInterval:y||"month"}),w=/^new_|^temp_/.test(String(e)),k=void 0!==p?1e4:v?2500:5e3;!w&&Object.keys(b).length>0&&(r(t=>(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>t.id===e?(0,o.A)((0,o.A)({},t),b):t)})),s(t=>(null===t||void 0===t?void 0:t.id)===e?(0,o.A)((0,o.A)({},t),b):t)),I.current=!0,v&&f(!0);const A=()=>{r(t=>(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>t.id===e?(0,o.A)((0,o.A)({},t),b):t)})),s(t=>(null===t||void 0===t?void 0:t.id)===e?(v&&(0,po.g)("[Payment] setCurrentDoc with paymentUpdate",b),(0,o.A)((0,o.A)({},t),b)):t),setTimeout(()=>{I.current=!1,f(!1),(0,po.g)("[Payment] Ref cleared \u2013 snapshots will be applied again",{inFlightClearMs:k})},k)};try{if(w)return void A();const t=(0,ge.httpsCallable)((0,ge.getFunctions)(),"updateDocumentPaymentConfig");await t((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({documentId:e},void 0!==a&&{paymentEnabled:!!a}),void 0!==i&&{paymentAmountCents:null==i||""===i?null:Number(i)}),void 0!==l&&{paymentAmountFieldId:null==l||""===l?null:l}),void 0!==d&&{paymentRevealAfterSignature:!!d}),void 0!==c&&{paymentProductName:c||null}),void 0!==u&&{paymentReminderEnabled:!!u}),void 0!==m&&{paymentLinks:Array.isArray(m)?m:null}),void 0!==p&&{paymentSubscriptionEnabled:!!p}),void 0!==g&&{paymentSubscriptionAmountCents:null==g||""===g?null:Number(g)}),void 0!==h&&{paymentSubscriptionProductName:h||null}),void 0!==y&&{paymentSubscriptionInterval:y||"month"}
1)),A()}catch(j){console.error("updateDocumentPaymentConfig:",j),Ie.Ay.error("Failed to save payment settings."),I.current=!1,f(!1)}},[t,r,s]),L=null!==S?S:!(null===l||void 0===l||!l.paymentSubscriptionEnabled);return{paymentConfigOpen:u,setPaymentConfigOpen:m,paymentConfigUpdating:h,setPaymentConfigUpdating:f,paymentFixedAmountEditing:x,setPaymentFixedAmountEditing:b,paymentSubscriptionAmountEditing:A,setPaymentSubscriptionAmountEditing:j,paymentConfigUpdateInProgressRef:I,lastPaymentUpdateAtRef:D,lastPaymentEnabledOnAtRef:P,lastPaymentSubscriptionEnabledOnAtRef:T,paymentSubscriptionEnabledEffective:L,paymentButtonRef:R,lastPaymentDropdownOpenAtRef:O,updateDocumentPaymentConfig:F}}var xo=n(50797),bo=n(58487),wo=n(93017),ko=n(10386);function Ao(e){return Math.min(100,Math.max(0,e))}function jo(e){var t,n;let r=e.imageUrl,s=e.value,l=e.onChange,d=e.onCommit,c=e.disabled,u=void 0!==c&&c;const m=(0,i.useRef)(null),p=(0,i.useRef)(null),g=(0,i.useState)(null),h=(0,a.A)(g,2),f=h[0],y=h[1],v=(0,i.useState)(!1),x=(0,a.A)(v,2),b=x[0],w=x[1],k=(0,ao.vK)(s),A=(0,ao.RC)({naturalWidth:null===f||void 0===f?void 0:f.width,naturalHeight:null===f||void 0===f?void 0:f.height,boxWidth:null===(t=m.current)||void 0===t?void 0:t.clientWidth,boxHeight:null===(n=m.current)||void 0===n?void 0:n.clientHeight,zoom:k.zoom,fit:k.fit}),j=A.overflowX>.5||A.overflowY>.5,N=(0,i.useCallback)(e=>{if(u||!m.current||0!==e.button)return;const t=m.current,n=(0,ao.vK)(s),r=(0,ao.RC)({naturalWidth:null===f||void 0===f?void 0:f.width,naturalHeight:null===f||void 0===f?void 0:f.height,boxWidth:t.clientWidth,boxHeight:t.clientHeight,zoom:n.zoom,fit:n.fit});r.overflowX<=.5&&r.overflowY<=.5||(p.current={pointerId:e.pointerId,startClientX:e.clientX,startClientY:e.clientY,startPosition:n,overflowX:r.overflowX,overflowY:r.overflowY,latest:n},t.setPointerCapture(e.pointerId),w(!0),e.preventDefault())},[u,f,s]),C=(0,i.useCallback)(e=>{const t=p.current;if(!t||t.pointerId!==e.pointerId)return;const n=e.clientX-t.startClientX,r=e.clientY-t.startClientY,a=(0,o.A)((0,o.A)({},t.startPosition),{},{x:t.overflowX>0?Ao(t.startPosition.x-n/t.overflowX*100):t.startPosition.x,y:t.overflowY>0?Ao(t.startPosition.y-r/t.overflowY*100):t.startPosition.y});t.latest=a,l(a)},[l]),S=(0,i.useCallback)(e=>{var t,n;const r=p.current;!r||e&&r.pointerId!==e.pointerId||(p.current=null,w(!1),null!==(t=m.current)&&void 0!==t&&null!==(n=t.hasPointerCapture)&&void 0!==n&&n.call(t,r.pointerId)&&m.current.releasePointerCapture(r.pointerId),d(r.latest))},[d]),E=(0,i.useCallback)(e=>{if(u)return;const t=(0,ao.vK)(s);let n=null;"ArrowLeft"===e.key&&(n=(0,o.A)((0,o.A)({},t),{},{x:Ao(t.x-2)})),"ArrowRight"===e.key&&(n=(0,o.A)((0,o.A)({},t),{},{x:Ao(t.x+2)})),"ArrowUp"===e.key&&(n=(0,o.A)((0,o.A)({},t),{},{y:Ao(t.y-2)})),"ArrowDown"===e.key&&(n=(0,o.A)((0,o.A)({},t),{},{y:Ao(t.y+2)})),n&&(e.preventDefault(),l(n),d(n))},[u,l,d,s]),I=(0,i.useCallback)(e=>{const t=Number(e.target.value);Number.isFinite(t)&&l((0,ao.vK)((0,o.A)((0,o.A)({},k),{},{zoom:t})))},[l,k]),D=(0,i.useCallback)(()=>{d(k)},[d,k]),P=(0,i.useCallback)(e=>{const t="contain"===e?(0,o.A)((0,o.A)({},ao.Yy),{},{fit:"contain"}):(0,o.A)((0,o.A)({},k),{},{fit:"cover"});l(t),d(t)},[l,d,k]),T=(0,i.useCallback)(()=>{l((0,o.A)({},ao.Yy)),d((0,o.A)({},ao.Yy))},[l,d]),R=(0,ao.Hw)(k,{WebkitUserDrag:"none"});return(0,We.jsxs)("div",{children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,We.jsx)("p",{className:"text-xs font-medium text-on-surface-muted uppercase tracking-wide",children:"Framing"}),(0,We.jsxs)("button",{type:"button",onClick:T,disabled:u||(0,ao.Hj)(k),className:"inline-flex items-center gap-1 text-xs text-on-surface-muted hover:text-on-surface disabled:opacity-40 disabled:hover:text-on-surface-muted",children:[(0,We.jsx)(we.A,{className:"h-3 w-3"}),"Recenter"]})]}),(0,We.jsxs)("div",{className:"flex gap-3",children:[(0,We.jsxs)("div",{ref:m,role:"application","aria-label":"Drag to reposition the cover image, or use the arrow keys",tabIndex:u?-1:0,onPointerDown:N,onPointerMove:C,onPointerUp:S,onPointerCancel:S,onKeyDown:E,className:"relative flex-1 min-w-0 aspect-[2/1] overflow-hidden rounded-brand-lg border border-hairline bg-surface-sunken touch-none focus:outline-none focus:ring-2 focus:ring-focus-ring ".concat(u?"cursor-default":j?b?"cursor-grabbing":"cursor-grab":"cursor-default"),children:[(0,We.jsx)("img",{src:r,alt:"",className:"h-full w-full object-cover select-none",style:R,draggable:!1,onLoad:e=>
1{y({width:e.target.naturalWidth,height:e.target.naturalHeight})}}),b&&(0,We.jsx)("div",{className:"pointer-events-none absolute inset-0 grid grid-cols-3 grid-rows-3",children:Array.from({length:9}).map((e,t)=>(0,We.jsx)("div",{className:"border border-white/30"},t))}),!b&&j&&(0,We.jsxs)("div",{className:"pointer-events-none absolute bottom-2 left-1/2 -translate-x-1/2 inline-flex items-center gap-1 rounded-full bg-black/55 px-2 py-1 text-[11px] font-medium text-white",children:[(0,We.jsx)(wo.A,{className:"h-3 w-3"}),"Drag to reposition"]})]}),(0,We.jsxs)("div",{className:"hidden sm:block shrink-0",children:[(0,We.jsx)("div",{className:"w-16 h-16 overflow-hidden rounded-brand-lg border border-hairline bg-surface-sunken",children:(0,We.jsx)("img",{src:r,alt:"",className:"h-full w-full object-cover select-none",style:R,draggable:!1})}),(0,We.jsx)("p",{className:"mt-1 text-center text-[10px] text-on-surface-subtle",children:"List"})]})]}),(0,We.jsx)("div",{className:"mt-3 inline-flex rounded-brand-md border border-hairline p-0.5",role:"group","aria-label":"Cover image fit",children:[{value:"cover",label:"Fill card"},{value:"contain",label:"Whole image"}].map(e=>(0,We.jsx)("button",{type:"button",disabled:u,"aria-pressed":k.fit===e.value,onClick:()=>P(e.value),className:"px-2.5 py-1 text-xs font-medium rounded-brand-sm disabled:opacity-50 ".concat(k.fit===e.value?"bg-brand text-brand-on":"text-on-surface-muted hover:text-on-surface"),children:e.label},e.value))}),(0,We.jsxs)("div",{className:"mt-2 flex items-center gap-3",children:[(0,We.jsx)(ko.A,{className:"h-4 w-4 text-on-surface-muted shrink-0","aria-hidden":"true"}
1),(0,We.jsx)("input",{type:"range",min:ao.F_,max:ao.pt,step:.05,value:k.zoom,disabled:u,onChange:I,onPointerUp:D,onKeyUp:D,onBlur:D,"aria-label":"Cover image zoom",className:"flex-1 accent-brand disabled:opacity-50"}),(0,We.jsx)(F.A,{className:"h-4 w-4 text-on-surface-muted shrink-0","aria-hidden":"true"}),(0,We.jsxs)("span",{className:"w-10 shrink-0 text-right text-xs tabular-nums text-on-surface-muted",children:[k.zoom.toFixed(1),"\xd7"]})]}),!j&&f&&(0,We.jsx)("p",{className:"mt-2 text-xs text-on-surface-subtle",children:"contain"===k.fit?"The whole image is visible. Cards pad the leftover space where the shapes differ.":"This image already fits the card exactly \u2014 zoom in to be able to reposition it."})]})}var No=n(18053);const Co=e=>{let t=e.children;if("undefined"===typeof document)return null;let n=document.getElementById("modal-root");return n||(n=document.createElement("div"),n.id="modal-root",document.body.appendChild(n)),(0,s.createPortal)(t,n)};function So(e){let t=e.isOpen,n=e.onClose,r=e.docId,s=e.title,l=e.fileName,d=e.setCoverImageUrl,u=e.setCoverImagePosition,m=e.clearCoverImage,g=e.searchPexelsForCover,h=e.randomPexelsCoverImage,f=e.cycleDocumentCoverImage,v=e.fetchCoverImage;const x=(0,i.useRef)(null),b=(0,i.useState)({coverImageUrl:null,documentImageUrls:[],textPreview:""}),w=(0,a.A)(b,2),k=w[0],A=w[1],j=(0,i.useState)((0,o.A)({},ao.Yy)),N=(0,a.A)(j,2),C=N[0],S=N[1],E=(0,i.useState)(!1),I=(0,a.A)(E,2),D=I[0],P=I[1],T=(0,i.useRef)(ao.Yy),R=(0,i.useState)(!1),O=(0,a.A)(R,2),F=O[0],L=O[1],U=(0,i.useState)(null),M=(0,a.A)(U,2),z=M[0],W=M[1],V=(0,i.useState)(""),J=(0,a.A)(V,2),q=J[0],H=J[1],K=(0,i.useState)([]),Q=(0,a.A)(K,2),Y=Q[0],Z=Q[1],$=(0,i.useState)(null),X=(0,a.A)($,2),ee=X[0],te=X[1],ne=(0,i.useState)(""),re=(0,a.A)(ne,2),oe=re[0],ae=re[1],ie=s&&String(s).trim()||l&&String(l).trim()||"Untitled Document",se=(0,i.useCallback)(async()=>{if(r){L(!0);try{const e=await(0,B.getDoc)((0,B.doc)(G.db,"knowledgeBaseDocuments",r)),t=e.exists()?e.data():{},n=!t.isEncrypted&&t.textContent&&"[Encrypted Content]"!==t.textContent?String(t.textContent).slice(0,200):"";A({coverImageUrl:t.coverImageUrl||null,documentImageUrls:Array.isArray(t.documentImageUrls)?t.documentImageUrls:[],textPreview:n});const o=(0,ao.vK)(t.coverImagePosition);T.current=o,S(o)}catch(e){console.error(e),Ie.Ay.error("Could not load document")}finally{L(!1)}}},[r]);(0,i.useEffect)(()=>{t&&r&&(Z([]),te(null),ae(""),H((0,co.Q4)(s||l,"")),se())},[t,r,s,l,se]);const le=async(e,t)=>{W(e);try{await t()}catch(n){console.error(n),Ie.Ay.error((null===n||void 0===n?void 0:n.message)||"Something went wrong")}finally{W(null)}},de=()=>{const e=q.trim();e?le("pexelsSearch",async()=>{const t=await g(e,{page:1,perPage:20}),n=t.photos,r=t.totalResults,o=t.page,a=t.perPage;Z(n),te({lastPage:o,perPage:a,totalResults:r,lastFetchCount:n.length}),0===n.length&&Ie.Ay.error("No photos found. Try different words.")}):Ie.Ay.error("Enter a search term")},ce=null!=ee&&Y.length>0&&(null!=ee.totalResults?ee.totalResults>0&&ee.lastPage*ee.perPage<ee.totalResults:(ee.lastFetchCount||0)>=ee.perPage),ue=(0,i.useCallback)(async e=>{if(!r||!u)return;const t=(0,ao.vK)(e);if(!(0,ao.ee)(t,T.current)){T.current=t,P(!0);try{await u(r,t)}catch(n){console.error(n),Ie.Ay.error("Could not save cover framing")}finally{P(!1)}}},[r,u]);if(!t)return null;const me=k.documentImageUrls.length>0,pe=!!k.coverImageUrl;return(0,We.jsx)(Co,{children:(0,We.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",role:"dialog","aria-modal":"true","aria-labelledby":"document-cover-modal-title",onClick:e=>{e.target===e.currentTarget&&n()},children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between border-b border-gray-200 px-4 py-3",children:[(0,We.jsxs)("h2",{id:"document-cover-modal-title",className:"text-lg font-medium text-gray-900 truncate pr-2",children:["Cover for ",ie]}),(0,We.jsx)("button",{type:"button",onClick:n,className:"p-1 rounded-md text-gray-500 hover:bg-gray-100 hover:text-gray-700","aria-label":"Close",children:(0,We.jsx)(c.A,{className:"h-5 w-5"})})]}),(0,We.jsx)("div",{className:"overflow-y-auto px-4 py-4 space-y-5 flex-1",children:F?(0,We.jsx)("div",{className:"flex justify-center py-8",children:(0,We.jsx)(Se.y$,{size:"md",className:"text-indigo-600"})}):(0,We.jsxs)(We.Fragment,{children:[pe&&(0,We.jsxs)("div",{children:[(0,We.jsx)(jo,{imageUrl:(0,ro.a)(k.coverImageUrl,{width:640}),value:C,onChange:S,onCommit:ue,disabled:!u||!!z}),D&&(0,We.jsx)("p",{className:"mt-2 text-xs text-on-surface-subtle",children:"Saving framing\u2026"})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("p",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-2",children:"Upload"}),(0,We.jsx)("input",{ref:x,type:"file",accept:"image/*",className:"hidden",onChange:e=>{var t,n;const o=null===(t=e.target.files)||void 0===t?void 0:t[0];if(e.target.value="",!o)return;if(!o.type.startsWith("image/"))return void Ie.Ay.error("Please choose an image file");const a=null===(n=G.j2.currentUser)||void 0===n?void 0:n.uid;a?le("upload",async()=>{const e=await(0,No.j1)(o),t=e.blob,n=e.extension,i=e.metadata,s=(0,Ee.KR)(G.IG,"users/".concat(a,"/knowledgeBase/").concat(r,"/cover-").concat(Date.now(),".").concat(n));await(0,Ee.D)(s,t,i);const l=await(0,Ee.qk)(s);await d(r,l,{showToast:!0}),await se()}):Ie.Ay.error("You must be signed in to upload")}}),(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:()=>{var e;return null===(e=x.current)||void 0===e?void 0:e.click()},className:"inline-flex items-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md disabled:opacity-50",children:["upload"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(xo.A,{className:"h-4 w-4"}),"Choose image file"]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("p",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-2",children:"Image URL"}),(0,We.jsxs)("div",{className:"flex gap-2",children:[(0,We.jsx)("input",{type:"url",value:oe,onChange:e=>ae(e.target.value),placeholder:"https://\u2026",className:"flex-1 min-w-0 px-3 py-2 border border-gray-300 rounded-md text-sm",disabled:!!z}),(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:()=>{const e=oe.trim();e?/^https?:\/\/.+/i.test(e)?le("url",async()=>
1{try{await(t=e,new Promise((e,n)=>{const r=new Image,o=setTimeout(()=>n(new Error("timeout")),15e3);r.onload=()=>{clearTimeout(o),e()},r.onerror=()=>{clearTimeout(o),n(new Error("load failed"))},r.src=t}))}catch(n){return void Ie.Ay.error("Could not load that URL as an image. Check the link or try uploading instead.")}var t;await d(r,e,{showToast:!0}),await se()}):Ie.Ay.error("URL must start with http:// or https://"):Ie.Ay.error("Enter an image URL")},className:"shrink-0 inline-flex items-center gap-1 px-3 py-2 text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 rounded-md disabled:opacity-50",children:["url"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(bo.A,{className:"h-4 w-4"}),"Apply"]})]})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("p",{className:"text-xs font-medium text-gray-500 uppercase tracking-wide mb-2",children:"Stock photos (Pexels)"}),(0,We.jsxs)("div",{className:"flex gap-2 mb-2",children:[(0,We.jsx)("input",{type:"text",value:q,onChange:e=>H(e.target.value),onKeyDown:e=>"Enter"===e.key&&de(),placeholder:"Search\u2026",className:"flex-1 min-w-0 px-3 py-2 border border-gray-300 rounded-md text-sm",disabled:!!z}),(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:de,className:"shrink-0 inline-flex items-center gap-1 px-3 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md disabled:opacity-50",children:["pexelsSearch"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(_.A,{className:"h-4 w-4"}),"Search"]})]}),Y.length>0&&(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("div",{className:"grid grid-cols-4 gap-2 max-h-48 overflow-y-auto p-1",children:Y.map(e=>{var t;const n=function(e){var t,n,r,o,a;return(null===e||void 0===e||null===(t=e.src)||void 0===t?void 0:t.tiny)||(null===e||void 0===e||null===(n=e.src)||void 0===n?void 0:n.small)||(null===e||void 0===e||null===(r=e.src)||void 0===r?void 0:r.medium)||(null===e||void 0===e||null===(o=e.src)||void 0===o?void 0:o.landscape)||(null===e||void 0===e||null===(a=e.src)||void 0===a?void 0:a.original)}(e),o=null!==(t=e.id)&&void 0!==t?t:n;return(0,We.jsx)("button",{type:"button",disabled:!!z,onClick:()=>(e=>{const t=function(e){var t,n,r;return(null===e||void 0===e||null===(t=e.src)||void 0===t?void 0:t.landscape)||(null===e||void 0===e||null===(n=e.src)||void 0===n?void 0:n.medium)||(null===e||void 0===e||null===(r=e.src)||void 0===r?void 0:r.original)}(e);t&&le("pick",async()=>{await d(r,t,{showToast:!0}),await se()})})(e),className:"relative aspect-square rounded overflow-hidden border border-gray-200 hover:ring-2 hover:ring-indigo-500 focus:outline-none focus:ring-2 focus:ring-indigo-500 disabled:opacity-50",children:n?(0,We.jsx)("img",{src:n,alt:"",className:"w-full h-full object-cover"}):(0,We.jsx)("span",{className:"text-xs text-gray-400",children:"?"})},o)})}),ce&&(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:()=>{const e=q.trim();if(!e||!ee)return;const t=ee.lastPage+1;le("pexelsMore",async()=>{const n=await g(e,{page:t,perPage:ee.perPage}),r=n.photos,o=n.totalResults,a=n.page,i=n.perPage;Z(e=>{const t=new Set(e.map(e=>e.id).filter(e=>null!=e)),n=[...e];for(const o of r)null!=o.id&&t.has(o.id)||(null!=o.id&&t.add(o.id),n.push(o));return n}),te({lastPage:a,perPage:i,totalResults:o,lastFetchCount:r.length}),0===r.length&&Ie.Ay.error("No more photos for this search.")})},className:"mt-2 w-full inline-flex items-center justify-center gap-2 px-3 py-2 text-sm font-medium text-gray-700 bg-gray-50 border border-gray-200 rounded-md hover:bg-gray-100 disabled:opacity-50",children:["pexelsMore"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(y.A,{className:"h-4 w-4"}),"Load more photos"]})]}),(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:()=>{const e=(0,co.Q4)(ie,k.textPreview);le("random",async()=>{await h(r,e,k.coverImageUrl,{showToast:!0})&&await se()})},className:"mt-2 inline-flex items-center gap-2 text-sm text-indigo-600 hover:text-indigo-800 disabled:opacity-50",children:["random"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(ct.A,{className:"h-4 w-4"}),"Another random stock photo"]})]}),me&&(0,We.jsx)("div",{children:(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:()=>{le("cycle",async()=>{await f(r,k.coverImageUrl,{showToast:!0})&&await se()})},className:"inline-flex items-center gap-2 text-sm text-gray-700 hover:text-gray-900 disabled:opacity-50",children:["cycle"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(fe.A,{className:"h-4 w-4"}),"Next image from document (",k.documentImageUrls.length," in doc)"]})}),!pe&&v&&(0,We.jsx)("div",{children:(0,We.jsx)("button",{type:"button",disabled:!!z,onClick:()=>
1{if(!v)return;const e=(0,co.Q4)(ie,k.textPreview);e?le("auto",async()=>{await v(r,e),await se()}):Ie.Ay.error("Not enough content to suggest a cover image.")},className:"text-sm text-gray-600 hover:text-gray-900 underline disabled:opacity-50",children:"auto"===z?"Working\u2026":"Auto-suggest from title (first doc image or stock)"})}),pe&&(0,We.jsx)("div",{className:"pt-2 border-t border-gray-100",children:(0,We.jsxs)("button",{type:"button",disabled:!!z,onClick:()=>{le("remove",async()=>{await m(r,{showToast:!0}),await se()})},className:"inline-flex items-center gap-2 text-sm text-red-600 hover:text-red-800 disabled:opacity-50",children:["remove"===z?(0,We.jsx)(Se.y$,{size:"sm",className:"text-indigo-600"}):(0,We.jsx)(p.A,{className:"h-4 w-4"}),"Remove cover"]})})]})}),(0,We.jsx)("div",{className:"border-t border-gray-200 px-4 py-3 flex justify-end",children:(0,We.jsx)("button",{type:"button",onClick:n,className:"px-4 py-2 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md",children:"Done"})})]})})})}function Eo(e){let t=e.image,n=e.onClose;if(!t)return null;const r=t.previewUrl||t.url||"/api/files/".concat(t.fileName);return(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-70 z-50 flex items-center justify-center p-4",children:(0,We.jsxs)("div",{className:"relative max-w-6xl w-full max-h-screen flex flex-col",children:[(0,We.jsx)("button",{onClick:n,className:"absolute top-2 right-2 bg-white bg-opacity-80 rounded-full p-2 hover:bg-opacity-100 z-10","aria-label":"Close",children:(0,We.jsx)(c.A,{className:"h-5 w-5 text-gray-800"})}),(0,We.jsxs)("div",{className:"bg-white rounded-lg p-4 w-full h-full overflow-auto",children:[(0,We.jsx)("div",{className:"min-h-0 flex items-center justify-center",children:(0,We.jsx)("img",{src:r,alt:t.title||"Full size image",className:"max-w-full max-h-[80vh] object-contain",crossOrigin:"anonymous",onError:e=>{console.error("Error loading full image:",e),e.target.style.display="none",e.target.parentNode.innerHTML='<div class="text-red-500 p-4 text-center">Error loading image</div>'}})}),t.title&&(0,We.jsx)("div",{className:"text-center mt-2 text-sm text-gray-700",children:t.title})]})]})})}function Io(e){let t=e.doc;const n="image"===t.type||t.fileType&&t.fileType.startsWith("image/"),r=(0,_e.Od)(t,"Untitled Document");return(0,We.jsx)("div",{className:"w-16 h-16 bg-gray-50 flex items-center justify-center flex-shrink-0 rounded-lg overflow-hidden",children:n?(0,We.jsx)("img",{src:t.previewUrl||"/api/files/".concat(t.fileName),alt:r,className:"h-full w-full object-cover rounded-lg",crossOrigin:"anonymous"}):t.coverImageUrl?(0,We.jsx)(oo.D,{src:(0,ro.a)(t.coverImageUrl,{width:160}),alt:t.title||"Cover image",className:"h-full w-full object-cover rounded-lg",style:(0,ao.Hw)(t.coverImagePosition),width:64,height:64,fallback:(0,We.jsx)(Bn,{doc:t,className:"h-8 w-8"})}):(0,We.jsx)(Bn,{doc:t,className:"h-8 w-8"})})}function Do(e){let t=e.results,n=e.onResultClick,r=e.breadcrumbLabel,o=e.onBreadcrumbClick;const s=(0,i.useState)(null),l=(0,a.A)(s,2),d=l[0],c=l[1];return(0,We.jsxs)("div",{children:[o&&(0,We.jsxs)("nav",{"aria-label":"Breadcrumb",className:"mb-3 text-sm text-gray-500 flex items-center gap-2",children:[(0,We.jsx)("button",{type:"button",onClick:o,className:"text-gray-600 hover:text-gray-900 hover:underline",children:r||"Documents"}),(0,We.jsx)("span",{className:"text-gray-300",children:"/"}),(0,We.jsx)("span",{className:"text-gray-700",children:"Search Results"})]}),(0,We.jsxs)("div",{className:"pb-5 border-b border-gray-200 mb-6",children:[(0,We.jsx)("h1",{className:"text-3xl font-bold text-gray-900",children:"Search Results"}),(0,We.jsxs)("p",{className:"text-gray-500 mt-2",children:["Found ",t.length," documents"]})]}),(0,We.jsx)("div",{className:"space-y-4",children:t.map((e,t)=>{const r=e.document;return(0,We.jsx)("div",{className:"bg-white shadow-sm rounded-lg p-4 hover:bg-gray-50 cursor-pointer transition-all ".concat(d===r.id?"ring-2 ring-blue-500 bg-blue-50":""),onClick:()=>{return e=r.id,c(e),void n(e);var e},children:(0,We.jsxs)("div",{className:"flex items-start gap-4",children:[(0,We.jsx)(Io,{doc:r}),(0,We.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,We.jsx)("h2",{className:"text-lg font-medium text-gray-900 mb-2 truncate",children:(0,_e.Od)(r,"Untitled Document")}),r.category&&(0,We.jsx)("div",{className:"mb-2",children:(0,We.jsx)("div",{className:"bg-blue-100 text-blue-800 px-2 py-0.5 rounded text-xs inline-block",children:r.category})}),(0,We.jsxs)("div",{className:"flex items-center text-sm text-gray-500",children:[(0,We.jsxs)("span",{children:["Relevance: ",e.relevance,"%"]}),(0,We.jsx)("div",{className:"mx-2",children:"\u2022"}),(0,We.jsx)("span",{className:"text-gray-700 text-sm",children:e.explanation}),d===r.id&&(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("div",{className:"mx-2",children:"\u2022"}),(0,We.jsx)("span",{className:"text-blue-600",children:"Opening..."})]})]})]})]})},r.id||t)})})]})}function Po(e){let t=e.value,n=e.onQueryChange,r=e.isSearching,o=void 0!==r&&r,s=e.placeholder,l=void 0===s?"Search all documents...":s,d=e.onSubmit;
1const c=(0,i.useState)(null!==t&&void 0!==t?t:""),u=(0,a.A)(c,2),m=u[0],p=u[1],g=(0,i.useRef)(null);(0,i.useEffect)(()=>{""===t&&p("")},[t]),(0,i.useEffect)(()=>""===m.trim()?(g.current&&(clearTimeout(g.current),g.current=null),void n("")):(g.current=setTimeout(()=>{g.current=null,n(m)},300),()=>{g.current&&clearTimeout(g.current)}),[m,n]);return(0,We.jsx)("form",{onSubmit:e=>{e.preventDefault(),g.current&&(clearTimeout(g.current),g.current=null);const t=m.trim();n(t),d&&d(e,t)},children:(0,We.jsxs)("div",{className:"relative",children:[(0,We.jsx)("div",{className:"absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none",children:(0,We.jsx)(_.A,{className:"h-5 w-5 text-gray-400"})}),(0,We.jsx)("input",{type:"text",className:"block w-full pl-10 pr-10 py-2 border border-gray-300 rounded-md leading-5 bg-white placeholder-gray-500 focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm",placeholder:l,value:m,onChange:e=>p(e.target.value),"aria-busy":o}),o&&(0,We.jsx)("div",{className:"absolute inset-y-0 right-0 pr-3 flex items-center",children:(0,We.jsx)(Se.y$,{size:"sm",className:"text-blue-500"})})]})})}function To(e){var t;let n=e.sidebarOpen,r=e.isMobile,o=e.currentPage,a=e.toggleSidebar,i=e.onAddKnowledge,s=e.onCreateWithAI,l=e.workspaceList,d=e.setWorkspaceList,c=e.currentWorkspace,u=e.setCurrentWorkspaceObject,m=e.setCurrentWorkspace,p=e.activeView,g=e.setActiveView,h=e.fetchDocumentsForWorkspace,f=e.firestore,y=e.currentWorkspaceObject,v=e.currentUser,b=e.setCurrentPage,w=e.setCurrentDoc,k=e.hasUnsavedChanges,A=e.setShowUnsavedChangesModal,j=e.setPendingNavigation,N=e.manualSaveTriggerRef,C=e.setActiveTab,S=e.knowledgeBase,E=e.deriveKeyFromCredential,I=e.decryptText,D=e.currentOrganizationId,P=e.orgResolved,T=e.workspaceFetchCompleted,R=e.onFetchWorkspacesComplete,O=e.formUnreadByWorkspace,F=e.selectedDocumentFolderId,L=void 0===F?null:F,_=e.onSelectDocumentFolder,U=e.onCreateDocumentFolder;const M=n&&!(r&&o);return(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"fixed inset-y-0 left-0 transform ".concat(M?"translate-x-0":"-translate-x-full"," lg:translate-x-0 transition duration-200 ease-in-out z-20 w-64 bg-white border-r border-gray-200 flex flex-col"),children:[(0,We.jsx)("div",{className:"h-[72px] px-4 flex items-center shrink-0 ".concat(r?"":"border-b border-gray-200"),children:(0,We.jsxs)("button",{type:"button","data-tour":"add-documents-button",onClick:()=>{s?s():i()},className:"add-docs-button w-full flex items-center justify-center gap-2 px-4 py-3 bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium rounded-md transition-colors duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed",children:[(0,We.jsx)(x.A,{className:"w-4 h-4 shrink-0","aria-hidden":!0}),"New Document"]})}),(0,We.jsx)("div",{className:"flex-grow overflow-y-auto ".concat(r?"pt-0 pb-4":"py-4"),children:(0,We.jsx)("div",{className:"px-3",children:(0,We.jsx)(vn,{documents:null!==(t=null===S||void 0===S?void 0:S.documents)&&void 0!==t?t:[],workspaceList:l,setWorkspaceList:d,currentWorkspace:c,setCurrentWorkspaceObject:u,setCurrentWorkspace:m,activeView:p,setActiveView:g,fetchDocuments:h,firestore:f,currentWorkspaceObject:y,currentUser:v,currentOrganizationId:D,setCurrentPage:b,setCurrentDoc:w,hasUnsavedChanges:k,setShowUnsavedChangesModal:A,setPendingNavigation:j,manualSaveTriggerRef:N,setActiveTab:C,orgResolved:P,workspaceFetchCompleted:T,onFetchWorkspacesComplete:R,formUnreadByWorkspace:O,selectedDocumentFolderId:L,onSelectDocumentFolder:_,onCreateDocumentFolder:U})})}),(0,We.jsx)(Fr,{currentUser:v,knowledgeBase:S,workspaceList:l,deriveKeyFromCredential:E,decryptText:I,selectedOrganizationId:D,totalDocumentCount:S.totalDocumentCount})]}),r&&M&&(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-10",onClick:a,"aria-hidden":"true"})]})}function Ro(e){let t=e.folder,n=e.documentCount,r=void 0===n?0:n,o=e.layout,s=void 0===o?"grid":o,l=e.isDropTarget,h=void 0!==l&&l,f=e.canEdit,y=void 0!==f&&f,v=e.onOpen,x=e.onRename,b=e.onDelete,w=e.onDragOver,k=e.onDragLeave,A=e.onDrop;const j="".concat(r," document").concat(1!==r?"s":""),N=(0,i.useState)(!1),C=(0,a.A)(N,2),S=C[0],E=C[1],I=(0,i.useState)(!1),D=(0,a.A)(I,2),P=D[0],T=D[1],R=(0,i.useState)((null===t||void 0===t?void 0:t.name)||""),O=(0,a.A)(R,2),F=O[0],L=O[1],_=(0,i.useState)(!1),U=(0,a.A)(_,2),M=U[0],z=U[1],B=(0,i.useRef)(null),W=(0,i.useRef)(null);(0,i.useEffect)(()=>{P||L((null===t||void 0===t?void 0:t.name)||"")},[null===t||void 0===t?void 0:t.name,P]),(0,i.useEffect)(()=>{var e;P&&(null===(e=W.current)||void 0===e||e.focus())},[P]),(0,i.useEffect)(()=>
1{if(!S)return;const e=e=>{B.current&&!B.current.contains(e.target)&&E(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[S]);const V=async e=>{var n,r;null===e||void 0===e||null===(n=e.preventDefault)||void 0===n||n.call(e),null===e||void 0===e||null===(r=e.stopPropagation)||void 0===r||r.call(e);const o=F.trim();if(o&&!M&&x){z(!0);try{await x(t.id,o),T(!1)}catch(a){}finally{z(!1)}}},J=y&&(x||b)?(0,We.jsxs)("div",{ref:B,className:"grid"===s?"absolute top-2 right-2 z-20":"relative flex-shrink-0",onClick:e=>e.stopPropagation(),children:[(0,We.jsx)("button",{type:"button","data-no-drag":!0,className:"p-1.5 rounded text-gray-500 hover:text-gray-800 ".concat("grid"===s?"opacity-0 group-hover:opacity-100 focus:opacity-100 bg-white/95 shadow-sm hover:bg-white":"hover:bg-gray-100"),onClick:e=>{e.preventDefault(),e.stopPropagation(),E(e=>!e)},title:"Folder options","aria-label":"Options for folder ".concat(t.name),children:(0,We.jsx)(u.A,{className:"h-4 w-4"})}),S&&(0,We.jsxs)("div",{className:"absolute z-30 w-40 bg-white border border-gray-200 rounded-md shadow-lg py-1 ".concat("grid"===s?"top-full right-0 mt-1":"right-0 top-full mt-1"),children:[x&&(0,We.jsxs)("button",{type:"button",className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50",onClick:()=>{E(!1),L(t.name),T(!0)},children:[(0,We.jsx)(m.A,{className:"h-3.5 w-3.5"}),"Rename"]}),b&&(0,We.jsxs)("button",{type:"button",className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50",onClick:()=>{E(!1),b(t.id)},children:[(0,We.jsx)(p.A,{className:"h-3.5 w-3.5"}),"Delete folder"]})]})]}):null;return"list"===s?P?(0,We.jsxs)("form",{className:"w-full p-4 flex items-center gap-3 rounded-lg border border-brand bg-white shadow-sm",onSubmit:V,onClick:e=>e.stopPropagation(),children:[(0,We.jsx)("span",{className:"w-16 h-16 flex-shrink-0 rounded-lg bg-amber-50 flex items-center justify-center",children:(0,We.jsx)(g.A,{className:"h-8 w-8 text-amber-500",strokeWidth:1.75})}),(0,We.jsx)("input",{ref:W,value:F,onChange:e=>L(e.target.value),disabled:M,maxLength:60,className:"flex-1 min-w-0 px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-brand/30"}),(0,We.jsx)("button",{type:"submit",disabled:M||!F.trim(),className:"p-1.5 text-brand hover:bg-brand/10 rounded disabled:opacity-50",title:"Save",children:(0,We.jsx)(d.A,{className:"h-4 w-4"})}),(0,We.jsx)("button",{type:"button",onClick:()=>{T(!1),L(t.name)},className:"p-1.5 text-gray-500 hover:bg-gray-100 rounded",title:"Cancel",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]}):(0,We.jsxs)("div",{role:"button",tabIndex:0,onClick:v,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),null===v||void 0===v||v())},onDragOver:w,onDragLeave:k,onDrop:A,"aria-label":"Open folder ".concat(t.name,", ").concat(j),className:"group w-full text-left p-4 flex items-center gap-4 roun
1ded-lg border shadow-sm transition-all duration-200 cursor-pointer ".concat(h?"border-brand border-2 bg-brand/5":"border-gray-200 bg-white hover:border-gray-300 hover:shadow-md"),children:[(0,We.jsx)("span",{className:"w-16 h-16 flex-shrink-0 rounded-lg bg-amber-50 flex items-center justify-center",children:(0,We.jsx)(g.A,{className:"h-8 w-8 text-amber-500",strokeWidth:1.75})}),(0,We.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,We.jsx)("div",{className:"text-sm font-medium text-gray-900 truncate",children:t.name}),(0,We.jsx)("div",{className:"text-xs text-gray-500 mt-0.5",children:j})]}),J]}):P?(0,We.jsxs)("form",{className:"relative w-full h-[11.5rem] rounded-2xl border border-brand bg-amber-50 p-4 flex flex-col justify-center gap-2",onSubmit:V,onClick:e=>e.stopPropagation(),children:[(0,We.jsx)("p",{className:"text-[11px] font-medium uppercase tracking-wide text-amber-900/50",children:"Rename folder"}),(0,We.jsx)("input",{ref:W,value:F,onChange:e=>L(e.target.value),disabled:M,maxLength:60,className:"w-full px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-brand/30"}),(0,We.jsxs)("div",{className:"flex items-center gap-1",children:[(0,We.jsx)("button",{type:"submit",disabled:M||!F.trim(),className:"p-1.5 text-brand hover:bg-brand/10 rounded disabled:opacity-50",title:"Save",children:(0,We.jsx)(d.A,{className:"h-4 w-4"})}),(0,We.jsx)("button",{type:"button",onClick:()=>{T(!1),L(t.name)},className:"p-1.5 text-gray-500 hover:bg-white/60 rounded",title:"Cancel",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]})]}):(0,We.jsxs)("div",{role:"button",tabIndex:0,onClick:v,onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),null===v||void 0===v||v())},onDragOver:w,onDragLeave:k,onDrop:A,"aria-label":"Open folder ".concat(t.name,", ").concat(j),className:"group relative block w-full text-left transition-transform duration-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 cursor-pointer ".concat(h?"scale-[1.02]":"hover:-translate-y-0.5"),children:[J,(0,We.jsxs)("div",{className:"relative w-full h-[11.5rem] ".concat(h?"drop-shadow-[0_0_0_2px_#3b82f6]":""),children:[(0,We.jsx)("div",{className:"absolute inset-x-0 top-3 bottom-0 rounded-2xl bg-amber-400","aria-hidden":"true"}),(0,We.jsx)("div",{className:"absolute left-0 top-0 h-4 w-[34%] rounded-t-2xl bg-amber-400","aria-hidden":"true"}),(0,We.jsx)("div",{className:"absolute left-0 top-3 h-2 w-[34%] bg-amber-400","aria-hidden":"true"}),(0,We.jsx)("div",{className:"absolute left-2.5 right-2.5 top-[1.35rem] h-2.5 rounded-sm bg-white","aria-hidden":"true"}),(0,We.jsxs)("div",{className:"absolute inset-x-0 top-7 bottom-0 rounded-2xl bg-gradient-to-b from-amber-200 via-amber-300 to-amber-400 overflow-hidden",children:[(0,We.jsx)("div",{className:"absolute inset-0 pointer-events-none",style:{background:"linear-gradient(165deg, rgba(255,255,255,0.45) 0%, rgba(255,255,255,0) 42%)"},"aria-hidden":"true"}),(0,We.jsxs)("div",{className:"relative z-10 flex h-full flex-col justify-start px-3.5 pt-3.5 pb-3",children:[(0,We.jsx)("p",{className:"text-[11px] font-medium uppercase tracking-wide text-amber-900/50 leading-none",children:"Folder"}),(0,We.jsx)("h3",{className:"mt-1.5 text-[15px] font-semibold leading-snug tracking-tight text-amber-950 truncate pr-6",children:t.name}),(0,We.jsx)("p",{className:"mt-0.5 text-xs leading-snug text-amber-900/65 tabular-nums",children:j})]})]})]})]})}function Oo(e){let t=e.isOpen,n=e.folder,r=void 0===n?null:n,o=e.documentCount,s=void 0===o?0:o,l=e.onConfirm,d=e.onCancel,c=e.isConfirming,u=void 0!==c&&c;const m=(0,i.useState)("keep"),p=(0,a.A)(m,2),g=p[0],h=p[1],f=(0,i.useState)(""),y=(0,a.A)(f,2),v=y[0],x=y[1];(0,i.useEffect)(()=>{t&&(h("keep"),x(""))},[t,null===r||void 0===r?void 0:r.id]);const b=(null===r||void 0===r?void 0:r.name)||"Folder",w=(0,i.useMemo)(()=>v.trim()===b,[v,b]),k=!u&&("keep"===g||"withDocuments"===g&&w);return t&&r?(0,We.jsx)(Dn.Q,{children:(0,We.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 p-4",children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-lg p-6 w-full max-w-md",role:"dialog","aria-modal":"true","aria-labelledby":"delete-document-folder-title",children:[(0,We.jsx)("h3",{id:"delete-document-folder-title",className:"text-lg font-medium mb-2",children:"Delete folder?"}),(0,We.jsxs)("p",{className:"text-gray-600 text-sm mb-4",children:["Choose what happens to"," ",(0,We.jsxs)("span",{className:"font-medium text-gray-800",children:['"',b,'"']}),s>0?" and its ".concat(s," document").concat(1===s?"":"s","."):"."]}),(0,We.jsxs)("div",{className:"space-y-3 mb-4",children:[(0,We.jsxs)("label",{className:"flex gap-3 p-3 rounded-md border cursor-pointer ".concat("keep"===g?"border-brand bg-brand/5":"border-gray-200 hover:bg-gray-50"),children:[(0,We.jsx)("input",{type:"radio",name:"delete-folder-mode",className:"mt-1",checked:"keep"===g,disabled:u,onChange:()=>h("keep")}),(0,We.jsxs)("span",{children:[(0,We.jsx)("span",{className:"block text-sm font-medium text-gray-900",children:"Delete folder only"}),(0,We.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5",children:"Documents stay in the workspace and move back to All documents."})]})]}),(0,We.jsxs)("label",{className:"flex gap-3 p-3 rounded-md border cursor-pointer ".concat("withDocuments"===g?"border-red-400 bg-red-50":"border-gray-200 hover:bg-gray-50"),children:[(0,We.jsx)("input",{type:"radio",name:"delete-folder-mode",className:"mt-1",checked:"withDocuments"===g,disabled:u,onChange:()=>h("withDocuments")}),(0,We.jsxs)("span",{children:[(0,We.jsx)("span",{className:"block text-sm font-medium text-red-700",children:"Delete folder and documents"}),(0,We.jsx)("span",{className:"block text-xs text-red-600/80 mt-0.5",children:"Permanently deletes documents in this folder. Locked documents are skipped."})]})]})]}),"withDocuments"===g&&(0,We.jsxs)("div",{className:"mb-4",children:[(0,We.jsxs)("label",{htmlFor:"delete-folder-confirm-name",className:"block text-sm font-medium text-gray-700 mb-1",children:["Type ",(0,We.jsx)("span",{className:"font-semibold",children:b})," to confirm"]}),(0,We.jsx)("input",{id:"delete-folder-confirm-name",type:"text",value:v,onCh
1ange:e=>x(e.target.value),placeholder:b,disabled:u,autoComplete:"off",className:"block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-red-500 focus:border-red-500 sm:text-sm disabled:bg-gray-100"})]}),(0,We.jsxs)("div",{className:"flex justify-end gap-2",children:[(0,We.jsx)("button",{type:"button",onClick:d,disabled:u,className:"px-4 py-2 text-sm text-gray-700 bg-gray-100 hover:bg-gray-200 rounded disabled:opacity-50",children:"Cancel"}),(0,We.jsxs)("button",{type:"button",disabled:!k,onClick:()=>null===l||void 0===l?void 0:l(g),className:"inline-flex items-center justify-center gap-2 px-4 py-2 text-sm text-white rounded disabled:opacity-50 disabled:cursor-not-allowed ".concat("withDocuments"===g?"bg-red-600 hover:bg-red-700":"bg-red-500 hover:bg-red-600"),children:[u&&(0,We.jsx)(Se.y$,{size:"sm",className:"flex-shrink-0"}),"withDocuments"===g?"Delete folder & documents":"Delete folder"]})]})]})})}):null}var Fo=n(65469);function Lo(e){var t,n;const r={wordCount:0,emptySelection:!0,selectionSnippet:"",inTable:!1,inList:!1,parentNodeType:"",hasListBlocks:!1,hasTableInDoc:!1,hasBlockquote:!1,headingBlockCount:0,nearestHeading:null,headingBreadcrumbs:[],totalPlainLength:0};if(!e)return r;if("function"===typeof e.isDestroyed&&e.isDestroyed)return r;if(!e.state)return r;const o=e.state;if(!o||!o.doc)return r;const a=o.selection,i=a.from,s=a.to,l=a.empty,d=o.doc.resolve(i),c=String(e.getText()||""),u=(c.trim().length?c.trim().split(/\s+/):[]).length;let m="";if(!l)try{m=o.doc.textBetween(i,s," ").trim()}catch(b){m=""}const p=m.slice(0,200),g="function"===typeof e.isActive&&e.isActive("table"),h=!0===("function"===typeof e.isActive&&(e.isActive("listItem")||e.isActive("bulletList")||e.isActive("orderedList")||e.isActive("taskList"))),f=(null===(t=d.parent)||void 0===t||null===(n=t.type)||void 0===n?void 0:n.name)||"",y=function(e){const t={hasListBlocks:!1,hasTable:!1,hasBlockquote:!1,headingCount:0},n=e=>{e&&"object"===typeof e&&("heading"===e.type&&(t.headingCount+=1),"bulletList"!==e.type&&"orderedList"!==e.type&&"listItem"!==e.type&&"taskList"!==e.type&&"taskItem"!==e.type||(t.hasListBlocks=!0),"table"===e.type&&(t.hasTable=!0),"blockquote"===e.type&&(t.hasBlockquote=!0),Array.isArray(e.content)&&e.content.forEach(n))};Array.isArray(null===e||void 0===e?void 0:e.content)&&e.content.forEach(n);return t}("function"===typeof e.getJSON?e.getJSON():{type:"doc",content:[]}),v=function(e,t){let n=null;return e.doc.descendants((e,r)=>{if(r>=t)return!1;if(e.isBlock&&"heading"===e.type.name){var o,a;const t=null!==(o=null===(a=e.attrs)||void 0===a?void 0:a.level)&&void 0!==o?o:1,i=(e.textContent||"").trim();n={level:t,text:i.slice(0,120),pos:r}}}),n}(o,i),x=function(e,t,n){const r=[];return e.doc.descendants((e,n)=>{if(n>=t)return!1;if(e.isBlock&&"heading"===e.type.name){var o,a;const t=null!==(o=null===(a=e.attrs)||void 0===a?void 0:a.level)&&void 0!==o?o:1,i=(e.textContent||"").trim();r.push({pos:n,level:t,text:i.slice(0,80)})}return!0}),r.slice(-n)}(o,i,3);return{wordCount:u,emptySelection:l,selectionSnippet:p,inTable:g,inList:h,parentNodeType:f,hasListBlocks:y.hasListBlocks,hasTableInDoc:y.hasTable,hasBlockquote:y.hasBlockquote,headingBlockCount:y.headingCount,nearestHeading:v,headingBreadcrumbs:x,totalPlainLength:c.length}}const _o=[{id:"fb-clarity",label:"Tighten wording and structure",prompt:"Improve overall clarity, tighten redundant wording, and make section flow easier to follow."},{id:"fb-consistency",label:"Make headings and terms consistent",prompt:"Make section heading levels and key terms more consistent (parallel phrasing, clear hierarchy)."}],Uo={contract:{id:"fb-contract",label:"Tighten key commercial terms",prompt:"Clarify obligations, term length, and termination; keep a neutral professional tone."},nda:{id:"fb-nda",label:"Tighten confidentiality terms",prompt:"Clarify confidential information, exclusions, and duration; keep a neutral professional tone."},policy:{id:"fb-policy",label:"Clarify owners and steps",prompt:"Clarify who does what and any deadlines in plain, actionable language."},proposal:{id:"fb-proposal",label:"Sharpen scope and value",prompt:"Tighten the scope, deliverables, and what makes the offer strong; keep a persuasive but professional tone."},meeting_notes:{id:"fb-mn",label:"Clarify decisions and next steps",prompt:"Turn notes into clear decisions, owners, and follow-up dates where implied."},invoice:{id:"fb-inv",label:"Clarify amounts and terms",prompt:"Make line items, totals, and due/payment terms crystal clear."}};function Mo(e,t){var n;if(e.inTable)return"E.g. clarify the table headers and make numeric formatting consistent in this table.";if(e.inList)return"E.g. add one sentence of useful detail to each list item in this list.";const r=((null===(n=e.nearestHeading)||void 0===n?void 0:n.text)||"").trim();if(r){const e=r.replace(/"/g,"''");return'E.g. tighten the "'.concat(e.slice(0,60)).concat(e.length>60?"\u2026":"",'" section and remove overlap with other sections.').slice(0,200)}const o=t&&String(t)||"auto";if("auto"!==o&&Uo[o]){if("invoice"===o)return"E.g. align all payment terms to Net 30 and verify line-item totals match the subtotal.";if("contract"===o)return"E.g. add a short termination-for-convenience clause and align it with the notice period elsewhere."}return"Describe the change you want \u2014 e.g. add a termination clause, shorten the intro, fix dates to Net 30\u2026".slice(0,200)}function zo(e,t){const n=[],r=t&&String(t)||"auto";if(e.inTable&&n.push({id:"in-table",label:"Tighten this table",prompt:"Tighten this table: clarify headers, align numeric or date formatting, and remove redundant cells without changing meaning."}),n.length<3&&e.inList&&n.push({id:"in-list",label:"Expand the current list",prompt:"Add a short clarifying line to each list item (or one sub-bullet per item) without changing structure."}),n.length<3&&"auto"!==r&&Uo[r]){const e=Uo[r];n.push({id:e.id,label:e.label,prompt:e.prompt})}return n.length<2&&n.push(..._o.filter(e=>!n.some(t=>t.id===e.id))),n.slice(0,3)}function Bo(e){if(!e||"string"!==typeof e)return"";let t=e;return t=t.replace(/^#{1,6}\s+/gm,""),t=t.replace(/\*\*([^*]+)\*\*/g,"$1"),t=t.replace(/\*([^*]+)\*/g,"$1"),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1"),t=t.replace(/^[\s>*+-]+/gm,""),t=t.replace(/\n{2,}/g,"\n"),t.trim()}const Wo=[{value:"auto",label:"Auto-detect"},{value:"proposal",label:"Proposal"},{value:"contract",label:"Contract / Agreement"},{value:"sow",label:"SOW"},{value:"nda",label:"NDA"},{value:"policy",label:"Policy / SOP"},{value:"letter",label:"Letter"},{value:"meeting_notes",label:"Meeting Notes"},{value:"one_pager",label:"One-Pager"},{value:"invoice",label:"Invoice"},{value:"other",label:"Other"}],Vo=[{value:"professional",label:"Professional"},{value:"friendly",label:"Friendly"},{value:"formal",label:"Formal"},{value:"brief",label:"Brief"}],Jo=120,qo=.4,Ho=12e4;const Go=/^[A-Za-z0-9_-]+$/;function Ko(e){const t=String(e||"").trim()||"Untitled";return Go.test(t)?"@".concat(t):'@"'.concat(t.replace(/"/g,"'"),'"')}function Qo(e){const t="string"===typeof e?e:"";if(!t)return null;const n=[],r=/@"([^"]+)"|@([A-Za-z0-9_-]+)/g;let o,a=0;for(;o=r.exec(t);){const e=o.index,i=r.lastIndex;e>a&&n.push(t.slice(a,e));const s=(o[1]||o[2]||"").trim();if(s?n.push((0,We.jsxs)("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full border border-blue-200 bg-blue-50 text-blue-800 text-[0.92em] align-baseline",children:["@",s]},"m-".concat(e,"-").concat(i))):n.push(t.slice(e,i)),a=i,n.length>300)break}return a<t.length&&n.push(t.slice(a)),n}const Yo=["Net 15","Net 30","Net 60","Custom"],Zo=["30 days","60 days","90 days","1 year","Custom"],$o=["Tomorrow","Next week","Next month","Custom"];function Xo(e,t){const n=new Date(e);return n.setDate(n.getDate()+t),n}function ea(e,t){return new Date(e.getFullYear(),e.getMonth()+t,e.getDate())}function ta(e){return e.toLocaleDateString("undefined"!==typeof navigator?navigator.language:"en-US",{year:"numeric",month:"long",day:"numeric"})}function na(e){if(!e||!/^\d{4}-\d{2}-\d{2}$/.test(e))return null;const t=e.split("-").map(e=>parseInt(e,10)),n=(0,a.A)(t,3),r=n[0],o=n[1],i=n[2];return new Date(r,o-1,i)}function ra(e,t){const n=e.trim().toLowerCase(),r=e.match(/^net\s*(\d+)$/i);if(r){const e=parseInt(r[1],10);if(Number.isFinite(e))return Xo(t,e)}if(/^\d+\s*days?$/i.test(e)){const n=e.match(/^(\d+)/);if(n)return Xo(t,parseInt(n[1],10))}return/^1\s*year$/i.test(e)?ea(t,12):"tomorrow"===n?Xo(t,1):"next week"===n?Xo(t,7):"next month"===n?ea(t,1):null}function oa(e){return"string"===typeof e?e:(null===e||void 0===e?void 0:e.question)||""}function aa(e){if(null==e||""===e)return"";const t=String(e).replace(/,/g,"");if(""===t||"."===t)return t;const n=parseFloat(t);
1return Number.isFinite(n)?n.toLocaleString("undefined"!==typeof navigator?navigator.language:"en-US",{minimumFractionDigits:0,maximumFractionDigits:2}):t}function ia(e,t,n){const r=(0,i.useCallback)(()=>{const t=e.current;if(!t)return;t.style.height="auto";const n=Math.min(window.innerHeight*qo,420),r=Math.max(Jo,Math.min(t.scrollHeight,n));t.style.height="".concat(r,"px")},[e]);(0,i.useEffect)(()=>{n&&r()},[t,n,r]),(0,i.useEffect)(()=>{if(!n)return;const e=()=>r();return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[n,r])}function sa(e){return e&&"object"===typeof e?{documentType:e.documentType||"auto",tone:e.tone||"professional",useCompanyInfo:!1!==e.useCompanyInfo,useWorkspaceDocuments:!0===e.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(e.pinnedDocumentIds)?e.pinnedDocumentIds.filter(Boolean):[]}:null}function la(e){var t,n,r,l,d;let u=e.open,m=e.onClose,p=e.onFormSubmit,g=e.onClarifySubmit,h=e.onBackFromClarify,f=e.onIntegrationsContinue,y=e.onEnableIntegration,v=e.loading,x=e.loadingMessage,b=e.phase,w=e.clarifyQuestions,k=e.integrationSuggestedIds,j=void 0===k?[]:k,N=e.integrationSnapshot,C=void 0===N?null:N,S=e.integrationEnablingId,E=void 0===S?null:S,I=e.integrationLookupLoading,D=void 0!==I&&I,T=e.showSignaturePadUnsureCheckbox,O=void 0!==T&&T,F=e.flow,L=void 0===F?"create":F,_=e.formSeedKey,U=void 0===_?0:_,M=e.formSeedDefaults,z=void 0===M?null:M,B=e.getEditorForSuggestions,W=e.suggestUpdateWorkspaceId,V=void 0===W?null:W,J=e.onCreateBlank,q=e.workspaceDocumentsForPicker,H=void 0===q?null:q,G=e.initialPrompt,K=void 0===G?"":G,Q=e.initialUpdateUserPrompt,Y=void 0===Q?"":Q;const Z=(0,i.useState)(""),$=(0,a.A)(Z,2),X=$[0],ee=$[1],te=(0,i.useState)("auto"),ne=(0,a.A)(te,2),re=ne[0],oe=ne[1],ae=(0,i.useState)("professional"),ie=(0,a.A)(ae,2),se=ie[0],le=ie[1],de=(0,i.useState)(!0),ce=(0,a.A)(de,2),ue=ce[0],me=ce[1],pe=(0,i.useState)(!0),fe=(0,a.A)(pe,2),ye=fe[0],ve=fe[1],xe=(0,i.useState)(!0),be=(0,a.A)(xe,2),we=be[0],ke=be[1],Ae=(0,i.useState)({}),je=(0,a.A)(Ae,2),Ne=je[0],Ce=je[1],Se=(0,i.useState)(0),De=(0,a.A)(Se,2),Pe=De[0],Te=De[1],Re=(0,i.useState)({}),Oe=(0,a.A)(Re,2),Fe=Oe[0],Le=Oe[1],_e=(0,i.useRef)(null),Ue=(0,i.useRef)(null),Me=(0,i.useRef)(null),ze=(0,i.useRef)(null),Be=(0,i.useRef)(null),Ve=(0,i.useState)(!1),Je=(0,a.A)(Ve,2),qe=Je[0],He=Je[1],Ge=(0,i.useRef)(null),Ke=(0,i.useState)([]),Qe=(0,a.A)(Ke,2),Ye=Qe[0],Ze=Qe[1],$e=(0,i.useState)(!1),Xe=(0,a.A)($e,2),et=Xe[0],tt=Xe[1],nt="undefined"!==typeof window&&"function"===typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches,rt="update"===L,ot=(0,i.useState)("idle"),at=(0,a.A)(ot,2),it=at[0],st=at[1],lt=(0,i.useState)([]),dt=(0,a.A)(lt,2),ut=dt[0],mt=dt[1],pt=(0,i.useState)(""),gt=(0,a.A)(pt,2),ht=gt[0],ft=gt[1],yt=(0,i.useState)(!1),vt=(0,a.A)(yt,2),xt=vt[0],bt=vt[1];ia(_e,X,u&&"form"===b),(0,i.useEffect)(()=>{u||(Ze([]),tt(!1))},[u]),(0,i.useEffect)(()=>{u&&"create"===L&&K&&ee(K)},[u,L,K]);const wt=(0,i.useState)(!1),kt=(0,a.A)(wt,2),At=kt[0],jt=kt[1],Nt=(0,i.useState)(""),Ct=(0,a.A)(Nt,2),St=Ct[0],Et=Ct[1],It=(0,i.useState)(null),Dt=(0,a.A)(It,2),Pt=Dt[0],Tt=Dt[1],Rt=(0,i.useState)(0),Ot=(0,a.A)(Rt,2),Ft=Ot[0],Lt=Ot[1],_t=(0,i.useState)(!1),Ut=(0,a.A)(_t,2),Mt=Ut[0],zt=Ut[1],Bt=(0,i.useMemo)(()=>(Array.isArray(H)?H:[]).map(e=>({id:e&&null!=e.id?String(e.id):"",title:e&&null!=e.title?String(e.title).trim():""})).filter(e=>e.id&&e.title),[H]),Wt=(0,i.useMemo)(()=>{if(!At)return[];const e=String(St||"").trim().toLowerCase(),t=Bt;return(e?t.filter(t=>t.title.toLowerCase().includes(e)):t).slice(0,8)},[At,St,Bt]),Vt=(0,i.useMemo)(()=>{const e=function(e){const t="string"===typeof e?e:"",n=[],r=/@"([^"]+)"|@([A-Za-z0-9_-]+)/g;let o;for(;o=r.exec(t);){const e=(o[1]||o[2]||"").trim();if(e&&n.push(e.slice(0,200)),n.length>=20)break}return n}(X);return e.length?function(e,t){const n=Array.isArray(t)?t:[],r=new Map,o=new Map;for(const l of n){const e=l&&null!=l.id?String(l.id):"",t=l&&null!=l.title?String(l.title).trim():"";if(!e||!t)continue;(r.get(t)||r.set(t,[]).get(t)).push(e);const n=t.toLowerCase();(o.get(n)||o.set(n,[]).get(n)).push(e)}const a=[],i=[],s=new Set;for(const l of Array.isArray(e)?e:[]){const e=String(l||"").trim();if(!e)continue;
1const t=r.get(e)||null,n=o.get(e.toLowerCase())||null,d=(t&&t.length?t:n)||[];if(!d.length){i.push("Couldn\u2019t find a document titled \u201c".concat(e,"\u201d."));continue}if(d.length>1){i.push("Multiple documents match \u201c".concat(e,"\u201d. Please pick the right one from the @ menu."));continue}const c=d[0];if(s.has(c)||(a.push(c),s.add(c)),a.length>=10)break}return{pinnedDocumentIds:a,errors:i}}(e,H):{pinnedDocumentIds:[],errors:[]}},[X,H]),Jt=Vt.errors[0]||"",qt=Vt.errors.length>0,Ht=(0,i.useCallback)(()=>{jt(!1),Et(""),Tt(null),Lt(0)},[]),Gt=(0,i.useCallback)((e,t)=>{if(!Bt.length)return void Ht();const n="number"===typeof t&&t>=0?t:e.length,r=e.slice(0,n),o=r.lastIndexOf("@");if(-1===o)return void Ht();const a=o>0?e[o-1]:"";if(o>0&&" "!==a&&"\n"!==a)return void Ht();const i=r.slice(o+1);if(!i.length)return jt(!0),Et(""),Tt(o),void Lt(0);i.includes("\n")||/\s/.test(i)||i.includes('"')?Ht():(jt(!0),Et(i),Tt(o),Lt(0))},[Bt.length,Ht]),Kt=(0,i.useCallback)(e=>{const t=_e.current;if(!t||null==Pt)return;const n=Pt,r="number"===typeof t.selectionStart?t.selectionStart:t.value.length;if(n>r)return;const o=X.slice(0,n),a=X.slice(r),i="".concat(Ko((null===e||void 0===e?void 0:e.title)||"Untitled")," "),s=o+i+a;Be.current=(o+i).length,ee(s),Ht(),requestAnimationFrame(()=>{const e=_e.current,t=Be.current;if(Be.current=null,!e||null==t)return;e.focus(),e.setSelectionRange(t,t),e.style.height="auto";const n=Math.min(window.innerHeight*qo,420);e.style.height="".concat(Math.max(Jo,Math.min(e.scrollHeight,n)),"px")})},[X,Pt,Ht]),Qt=(0,i.useCallback)(()=>{const e=_e.current,t=Ue.current;e&&t&&(t.scrollTop=e.scrollTop,t.scrollLeft=e.scrollLeft)},[]);(0,i.useEffect)(()=>{At&&Wt.length?Lt(e=>Math.min(Math.max(0,e),Wt.length-1)):Lt(0)},[At,Wt]);const Yt=(0,i.useMemo)(()=>Array.isArray(w)?w:[],[w]),Zt=Yt.length,$t=Yt[Pe],Xt="string"===typeof $t?"text":$t&&"object"===typeof $t&&$t.type?$t.type:"text",en=!!$t&&function(e){if(!e||"string"===typeof e)return!1;if(e.multiline)return!0;const t="".concat(e.question||""," ").concat(e.subtitle||"").toLowerCase();return/description|services|products|detail|list|explain|summarize|paragraph|items|cover/.test(t)}($t);ia(ze,null!==(t=Ne[Pe])&&void 0!==t?t:"","clarify"===b&&"text"===Xt&&en);const tn=(0,i.useMemo)(()=>$t&&"date"===Xt?"object"===typeof $t&&Array.isArray($t.date_presets)&&$t.date_presets.length>0?$t.date_presets:function(e){return"invoice"===e?[...Yo]:"contract"===e||"proposal"===e||"sow"===e||"nda"===e?[...Zo]:[...$o]}(re):[],[$t,Xt,re]);(0,i.useEffect)(()=>{"integrations"===b&&He(!1)},[b]);const nn=(0,i.useMemo)(()=>rt?"loading"===it||"idle"===it?"Preparing a suggestion for your document\u2026":ht||"Describe the change you want \u2014 e.g. add a termination clause, shorten the intro, fix dates to Net 30\u2026":"Describe what you need \u2014 e.g. a subcontractor agreement for a roofing company in New Jersey",[rt,it,ht]);(0,i.useEffect)(()=>{if(u&&"form"===b){if(rt&&("loading"===it||"idle"===it))return;const e=requestAnimationFrame(()=>{var e;null===(e=_e.current)||void 0===e||e.focus();const t=_e.current;if(t){t.style.height="auto";const e=Math.min(window.innerHeight*qo,420);t.style.height="".concat(Math.max(Jo,Math.min(t.scrollHeight,e)),"px")}});return()=>cancelAnimationFrame(e)}},[u,b,rt,it]),(0,i.useEffect)(()=>{u||(ee(""),oe("auto"),le("professional"),me(!0),ve(!0),ke(!0),Ce({}),Te(0),Le({}),jt(!1),Et(""),Tt(null),Lt(0),zt(!1),st("idle"),mt([]),ft(""),bt(!1))},[u]),(0,i.useEffect)(()=>{if(!u||!rt||"form"!==b||!U)return;const e=sa(z);if(!e)return;oe(e.documentType),le(e.tone),me(e.useCompanyInfo),ve(e.useWorkspaceDocuments);const t=Array.isArray(e.pinnedDocumentIds)?e.pinnedDocumentIds.filter(Boolean).slice(0,10):[];if(t.length&&Bt.length){const e=[];for(const n of t){const t=Bt.find(e=>e.id===String(n));t&&e.push(Ko(t.title))}e.length&&ee(e.join(" "))}},[u,rt,b,U,z,Bt]),(0,i.useEffect)(()=>{if(!u||!rt||"form"!==b||!U)return;const e="string"===typeof Y?Y.trim():"";e&&ee(e)},[u,rt,b,U,Y]);const rn=(0,i.useRef)(B);rn.current=B,(0,i.useEffect)(()=>{if(!u||!rt||"form"!==b||!U)return;if("function"!==typeof rn.current)return bt(!0),st("ready"),void mt([]);const e=rn.current,t=e();if(!t||"function"===typeof t.isDestroyed&&t.isDestroyed||!t.getText)return bt(!0),st("ready"),mt(zo({wordCount:0,emptySelection:!0,selectionSnippet:"",inTable:!1,inList:!1,parentNodeType:"",hasListBlocks:!1,hasTableInDoc:!1,hasBlockquote:!1,headingBlockCount:0,nearestHeading:null,headingBreadcrumbs:[],totalPlainLength:0},"auto")),void ft("Describe the change you want \u2014 e.g. add a termination clause, shorten the intro, fix dates to Net 30\u2026");const n=String(t.getText()||"").trim().slice(0,Jn.s$);if(!n)return st("ready"),mt([]),void ft("Describe the change you want \u2014 e.g. add a termination clause, shorten the intro, fix dates to Net 30\u2026");const r=sa(z),o=(null===r||void 0===r?void 0:r.documentType)||"auto";let a=!1;return bt(!1),st("loading"),(async()=>{try{const t=await(0,Jn.ib)({documentExcerpt:n,documentType:o,workspaceId:V}),r=t.ideas,i=t.promptPlaceholder;if(a)return;const s=e(),l=s&&"function"===typeof s.isDestroyed&&!s.isDestroyed?Lo(s):{wordCount:0,emptySelection:!0,selectionSnippet:"",inTable:!1,inList:!1,parentNodeType:"",hasListBlocks:!1,hasTableInDoc:!1,hasBlockquote:!1,headingBlockCount:0,nearestHeading:null,headingBreadcrumbs:[],totalPlainLength:0};mt(Array.isArray(r)?r:[]);
1const d=i&&String(i).trim()?String(i).trim():Mo(l,o);ft(d),st("ready")}catch(t){if(a)return;const n=e(),r=n&&"function"===typeof n.isDestroyed&&!n.isDestroyed?Lo(n):{wordCount:0,emptySelection:!0,selectionSnippet:"",inTable:!1,inList:!1,parentNodeType:"",hasListBlocks:!1,hasTableInDoc:!1,hasBlockquote:!1,headingBlockCount:0,nearestHeading:null,headingBreadcrumbs:[],totalPlainLength:0};bt(!0),mt(zo(r,o)),ft(Mo(r,o)),st("ready")}})(),()=>{a=!0}},[u,rt,b,U,z,V]);const on=(0,i.useCallback)(e=>{const t=rn.current,n="function"===typeof t?t():null,r=function(e,t){const n=String(t||"").trim();if(!n)return"";const r=String(e.selectionSnippet||"").trim();if(!r||e.emptySelection)return n;const o=r.length>120?"".concat(r.slice(0,120),"\u2026"):r;return'For the current selection (starts: "'.concat(o,'"): ').concat(n)}(n&&"function"===typeof n.isDestroyed&&!n.isDestroyed?Lo(n):{wordCount:0,emptySelection:!0,selectionSnippet:"",inTable:!1,inList:!1,parentNodeType:"",hasListBlocks:!1,hasTableInDoc:!1,hasBlockquote:!1,headingBlockCount:0,nearestHeading:null,headingBreadcrumbs:[],totalPlainLength:0},e.prompt);r&&(Ht(),ee(e=>(e.trim()?"".concat(e.trim(),"\n"):"")+r),requestAnimationFrame(()=>{const e=_e.current;if(e){e.focus();const t=e.value.length;e.setSelectionRange(t,t),e.style.height="auto";const n=Math.min(window.innerHeight*qo,420);e.style.height="".concat(Math.max(Jo,Math.min(e.scrollHeight,n)),"px")}}))},[Ht]);(0,i.useEffect)(()=>{"clarify"===b&&Array.isArray(w)&&(Te(0),Ce(e=>{const t={};return w.forEach((n,r)=>{t[r]=null!=e[r]?e[r]:""}),t}),Le({}))},[b,w]),(0,i.useEffect)(()=>{if(!u||"clarify"!==b||!$t)return;const e=requestAnimationFrame(()=>{var e,t;null===(e=Me.current)||void 0===e||null===(t=e.focus)||void 0===t||t.call(e)});return()=>cancelAnimationFrame(e)},[u,b,Pe,$t,Xt]);const an=(0,i.useCallback)(()=>{var e;"undefined"!==typeof document&&null!==(e=document.activeElement)&&void 0!==e&&e.blur&&document.activeElement.blur()},[]),sn=(0,i.useCallback)(()=>({pinnedDocumentIds:Vt.pinnedDocumentIds,errors:Vt.errors}),[Vt]),ln=(0,i.useCallback)(async e=>{var t,n;const r=e.target,o=null===(t=r.files)||void 0===t?void 0:t[0];if(r&&(r.value=""),!o)return;const a=null===(n=(0,he.xI)().currentUser)||void 0===n?void 0:n.uid;if(a)if(o.name.toLowerCase().endsWith(".pdf"))if(o.size>52428800)Ie.Ay.error("PDF must be 50 MB or smaller.");else if(Ye.length>=1)Ie.Ay.error("You can only attach one PDF.");else{tt(!0);try{var i;const e=o.name.replace(/[^\w.\-()+ ]/g,"_"),t="users/".concat(a,"/pdf-extraction-tests/create-with-ai_").concat(Date.now(),"_").concat(e);await(0,Ee.D)((0,Ee.KR)((0,Ee.c7)(),t),o,{contentType:"application/pdf"});const n=(0,ge.httpsCallable)((0,ge.getFunctions)(),"extractPdfUpload"),r=await n({storagePath:t,includeImages:!1}),l=function(e){return e&&"object"===typeof e&&Array.isArray(e.chunks)?e.chunks.map(e=>e&&"string"===typeof e.text?e.text:"").join("\n\n").trim():""}(null===(i=r.data)||void 0===i?void 0:i.extraction);if(!l)return void Ie.Ay.error("No text could be extracted from that PDF.");const d=function(e){if(!e||"string"!==typeof e)return"";return function(e){if(!e||"string"!==typeof e)return"";let t=e.replace(/==>[^\n]*?omitted\s*<==/gi,"");return t=t.split("\n").map(e=>e.replace(/[ \t]+$/g,"")).join("\n"),t=t.replace(/\n{2,}/g,"\n"),t.trim()}(e).replace(/\*\*/g,"").split("\n").map(e=>{const t=e.trim();return/^\*(\s+\*){2,}\s*$/.test(t)?e:e.replace(/^(\s*)[+*-]\s+/,"$1- [ ] ")}).join("\n")}((s=l)&&"string"===typeof s?s.replace(/!\[[^\]]*\]\(data:image\/[^)]+\)/gi,"[_image omitted_]"):""),c=(0,Ee.KR)((0,Ee.c7)(),t),u=await(0,Ee.qk)(c);Ze(e=>e.length>=1?e:[...e,{id:"".concat(Date.now(),"_").concat(Math.random().toString(36).slice(2,9)),fileName:o.name,markdown:d,storagePath:t,downloadUrl:u}]),Ie.Ay.success("Added \u201c".concat(o.name,"\u201d as reference"))}catch(l){console.error("Create With AI \u2014 PDF context:",l),Ie.Ay.error((null===l||void 0===l?void 0:l.message)||"Could not extract PDF.")}finally{tt(!1)}var s}else Ie.Ay.error("Please choose a PDF file.");else Ie.Ay.error("Sign in to upload a PDF.")},[Ye.length]),dn=(0,i.useCallback)(e=>{Ze(t=>t.filter(t=>t.id!==e))},[]),cn=(0,i.useCallback)(()=>{const e=Ye[0];if(!e||"string"!==typeof e.markdown||!e.markdown.trim())return null;const t="string"===typeof e.fileName?e.fileName:"document.pdf",n={markdown:e.markdown,fileName:t};return"string"===typeof e.storagePath&&e.storagePath&&"string"===typeof e.downloadUrl&&e.downloadUrl?(0,o.A)((0,o.A)({},n),{},{storagePath:e.storagePath,downloadUrl:e.downloadUrl,markdownPlainText:Bo(e.markdown)}):n},[Ye]),un=(0,i.useCallback)(()=>{const e=function(e){if(!Array.isArray(e)||!e.length)return"";let t=e.map(e=>{const t="string"===typeof e.fileName?e.fileName:"document.pdf",n="string"===typeof e.markdown?e.markdown:"";return"### ".concat(t,"\n").concat(n)}).join("\n\n---\n\n");return t.length>Ho&&(t="".concat(t.slice(0,Ho),"\n\n[\u2026 reference text trimmed for length \u2026]")),t}(Ye),t=Ye[0],n={};return e&&(n.uploadedDocumentsContext=e),t&&"string"===typeof t.storagePath&&t.storagePath&&"string"===typeof t.downloadUrl&&t.downloadUrl&&"string"===typeof t.markdown&&t.markdown.trim()&&(n.pdfSource={storagePath:t.storagePath,downloadUrl:t.downloadUrl,fileName:"string"===typeof t.fileName?t.fileName:"document.pdf",markdown:t.markdown,markdownPlainText:Bo(t.markdown)}),n},[Ye]),mn=(0,i.useCallback)(()=>Array.isArray(w)?w.map((e,t)=>{var n;return{question:oa(e),answer:String(null!==(n=Ne[t])&&void 0!==n?n:"").trim()}}):[],[w,Ne]),pn=Zt>0&&Pe>=Zt-1,gn=(0,i.useCallback)(()=>{v||D||(pn?(an(),null===g||void 0===g||g({clarificationPairs:mn()})):Te(e=>Math.min(e+1,Math.max(0,Zt-1))))},[v,D,pn,g,mn,an,Zt]),hn=(0,i.useCallback)(()=>
1{if(v||D)return;const e=Pe,t=(0,o.A)({},Ne);if(Le(t=>{const n=(0,o.A)({},t);return delete n[e],n}),pn){an();const n=Yt.map((n,r)=>{var o;return{question:oa(n),answer:r===e?"":String(null!==(o=t[r])&&void 0!==o?o:"").trim()}});return Ce(t=>(0,o.A)((0,o.A)({},t),{},{[e]:""})),void(null===g||void 0===g||g({clarificationPairs:n}))}Ce(t=>(0,o.A)((0,o.A)({},t),{},{[e]:""})),Te(e=>Math.min(e+1,Math.max(0,Zt-1)))},[Pe,pn,g,an,Yt,Ne,Zt,v,D]),fn=(0,i.useCallback)(()=>{v||D||(Pe<=0?null===h||void 0===h||h():Te(e=>Math.max(0,e-1)))},[v,D,Pe,h]),yn=(0,i.useCallback)((e,t)=>{Ce(n=>(0,o.A)((0,o.A)({},n),{},{[e]:t}))},[]),vn="clarify"===b&&("currency"===Xt||"email"===Xt||"select"===Xt||"text"===Xt&&!en||"date"===Xt&&"custom"!==(null===(n=Fe[Pe])||void 0===n?void 0:n.mode));if((0,i.useEffect)(()=>{if(!u)return;const e=e=>{if("Escape"===e.key&&!v&&!D){if("clarify"===b)return;if("form"===b&&At)return e.preventDefault(),void Ht();e.preventDefault(),m()}if((e.metaKey||e.ctrlKey)&&"Enter"===e.key&&!v&&!D){if("update"===L&&("loading"===it||"idle"===it))return void e.preventDefault();if("form"===b&&!qt){if("create"===L&&!rt&&"function"===typeof J&&null!=cn()&&!X.trim()){e.preventDefault(),an();const t=cn();return void(t&&J(t))}if(X.trim()){e.preventDefault(),an();const t=sn(),n=t.pinnedDocumentIds;if(t.errors.length)return void Ht();p((0,o.A)({userPrompt:X.trim(),documentType:re,tone:se,useCompanyInfo:ue,useWorkspaceDocuments:ye,askClarification:we,pinnedDocumentIds:n.length?[...n]:void 0},un()))}}"clarify"===b&&(e.preventDefault(),an(),gn()),"create"!==L||"integrations"!==b||E||(e.preventDefault(),null===f||void 0===f||f({signatureBlocksInDraftUnsure:qe}))}if("Enter"===e.key&&!v&&!D&&!e.metaKey&&!e.ctrlKey&&"clarify"===b){var t;if(!vn)return;if("TEXTAREA"===(null===(t=document.activeElement)||void 0===t?void 0:t.tagName))return;e.preventDefault(),gn()}};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[u,v,D,m,p,b,X,re,se,ue,ye,we,At,Ht,sn,an,gn,vn,E,f,qe,L,it,qt,un,cn,rt,J]),!u)return null;const xn="gathering"===b,bn="loading"===b,wn="create"===L&&"integrations"===b,kn=v||xn||!!E||D,An="clarify"===b,jn=xn?"Checking what details we need\u2026":bn&&x?x:rt?"Updating your document\u2026":"Creating your document\u2026",Nn=xn?x&&"Checking what details we need\u2026"!==String(x).trim()?x:"One moment\u2026":bn&&x?"This may take a few seconds.":rt?"Applying your changes\u2026":"Generating your document\u2026",Cn=()=>{if(!X.trim()||v||D||qt)return;if(rt&&("loading"===it||"idle"===it))return;const e=sn(),t=e.pinnedDocumentIds;e.errors.length?Ht():p((0,o.A)({userPrompt:X.trim(),documentType:re,tone:se,useCompanyInfo:ue,useWorkspaceDocuments:ye,askClarification:we,pinnedDocumentIds:t.length?[...t]:void 0},un()))},Sn=!rt&&"function"===typeof J&&null!=cn(),En=Pe,In=Fe[En]||{},Dn=function(){const e=new Date;return e.setHours(12,0,0,0),e}(),Pn=e=>"inline-flex items-center px-3 py-1.5 rounded-full border text-sm cursor-pointer transition-colors ".concat(e?"border-blue-400 bg-blue-50 text-blue-800":"border-gray-200/90 text-gray-600 hover:bg-gray-50/80"),Tn=$t?oa($t):"";return(0,s.createPortal)((0,We.jsx)("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 bg-black/40 backdrop-blur-md",role:"dialog","aria-modal":"true","aria-labelledby":"create-with-ai-title",onMouseDown:e=>{e.target!==e.currentTarget||kn||m()},children:(0,We.jsxs)("div",{className:"relative max-w-2xl w-full max-h-[90vh] rounded-2xl p-[2px] overflow-hidden shadow-2xl shadow-blue-500/[0.04]",onMouseDown:e=>e.stopPropagation(),children:[(0,We.jsx)("div",{className:"pointer-events-none absolute left-1/2 top-1/2 h-[220%] w-[220%] min-h-[48rem] min-w-[48rem] -translate-x-1/2 -translate-y-1/2 animate-[spin_6s_linear_infinite] motion-reduce:animate-none opacity-45",style:{background:"conic-gradient(from 0deg at 50% 50%, transparent 0deg, transparent 44deg, rgba(59,130,246,0.04) 58deg, rgba(191,219,254,0.22) 76deg, rgba(59,130,246,0.05) 96deg, transparent 118deg, transparent 360deg)"},"aria-hidden":!0}),(0,We.jsxs)("div",{className:"relative z-10 flex max-h-[calc(90vh-4px)] flex-col overflow-hidden rounded-[14px] bg-white/95 ring-1 ring-black/5 backdrop-blur-sm",children:[(0,We.jsx)("h2",{id:"create-with-ai-title",className:"sr-only",children:bn?jn.replace(/\u2026$/,""):xn?"Preparing questions":"clarify"===b?"Fill in details":"integrations"===b?"Integrations for this draft":rt?"Update with AI":"Create with AI"}),"loading"===b||xn?(0,We.jsxs)("div",{role:"status","aria-live":"polite","aria-busy":"true",children:[(0,We.jsx)("div",{className:"flex items-center justify-between gap-3 px-5 pt-4 pb-2",children:(0,We.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,We.jsx)(ct.A,{className:"w-4 h-4 text-blue-600 shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-800 truncate",children:jn})]})}),(0,We.jsxs)("div",{className:"px-5 pb-5 space-y-4",children:[(0,We.jsx)("div",{className:"h-1.5 bg-gray-100 rounded-full overflow-hidden",children:(0,We.jsx)("div",{className:"h-full bg-blue-500 rounded-full animate-pulse",style:{width:xn?"40%":"55%"}})}),(0,We.jsx)("p",{className:"text-sm text-gray-600",children:Nn})]})]}):wn?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"flex items-center justify-between gap-3 px-5 pt-4 pb-2",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 text-gray-500 min-w-0",children:[(0,We.jsx)(ct.A,{className:"w-4 h-4 text-blue-500/90 shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{className:"text-xs font-medium tracking-wide uppercase",children:"Integrations"})]}),(0,We.jsx)("button",{type:"button",onClick:m,disabled:kn,className:"p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100/80 transition-colors disabled:opacity-50","aria-label":"Close",children:(0,We.jsx)(c.A,{className:"w-4 h-4"})})]}),(0,We.jsxs)("div",{className:"px-5 pb-2 space-y-4 min-h-0 max-h-[min(52vh,28rem)] overflow-y-auto",children:[(0,We.jsx)("p",{className:"text-sm text-gray-600",children:"Based on your request, these abilities may help. We will pass what is enabled into the AI. Tur
1n on any you want to use for this draft."}),(0,We.jsx)("ul",{className:"space-y-3",children:j.map(e=>{const t=Pr.u9[e]||e,n=Pr.Zg[e]||"",r=(0,Pr.Jm)(C,e),o="stripe"===e;return(0,We.jsxs)("li",{className:"rounded-lg border border-gray-100/90 bg-white/80 px-3 py-2.5 text-sm text-gray-800",children:[(0,We.jsx)("div",{className:"font-medium text-gray-900",children:t}),n?(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:n}):null,r?(0,We.jsx)("p",{className:"text-xs text-emerald-700 mt-2",children:"We will include this in context for the draft."}):o?(0,We.jsxs)("p",{className:"text-xs text-gray-600 mt-2",children:["Connect your Stripe account under"," ",(0,We.jsx)("a",{href:"/integrations",className:"text-blue-600 hover:underline font-medium",children:"Integrations"})," ","to add payment-ready language."]}):(0,We.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:[(0,We.jsx)("button",{type:"button",disabled:!!E,onClick:()=>null===y||void 0===y?void 0:y(e),className:"inline-flex items-center px-2.5 py-1 text-xs font-medium text-white bg-blue-500 rounded-md hover:bg-blue-600 disabled:opacity-50",children:E===e?"Turning on\u2026":"Turn on ".concat(t)}),(0,We.jsx)("span",{className:"text-xs text-gray-400",children:"Optional \u2014 you can skip and generate anyway."})]})]},e)})}),O?(0,We.jsxs)("label",{className:"flex items-start gap-2.5 cursor-pointer text-sm text-gray-800 mt-1",children:[(0,We.jsx)("input",{type:"checkbox",className:"mt-1 rounded border-gray-300 text-blue-600 focus:ring-blue-500",checked:qe,onChange:e=>He(e.target.checked)}),(0,We.jsx)("span",{children:"Include a formal signature area in this draft (for sending to sign in Based)"})]}):null]}),(0,We.jsx)("div",{className:"mt-auto border-t border-gray-100 bg-gray-50/60 rounded-b-[14px] px-5 py-3",children:(0,We.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,We.jsx)("div",{className:"min-w-0 flex-1 flex items-center",children:"function"===typeof J?null!==(r=Ye[0])&&void 0!==r&&r.fileName?(0,We.jsxs)("button",{type:"button",onClick:()=>J(cn()),disabled:!!E,className:"inline-flex items-center gap-1.5 max-w-full rounded-lg border border-blue-200 bg-blue-50 px-3 py-1.5 text-sm font-medium text-blue-800 hover:bg-blue-100 hover:border-blue-300 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Use \u201c".concat(Ye[0].fileName,"\u201d as a starting draft"),children:[(0,We.jsx)(R.A,{className:"w-3.5 h-3.5 shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{className:"shrink-0",children:"Use"}),(0,We.jsxs)("span",{className:"truncate",children:["\u201c",Ye[0].fileName,"\u201d"]})]}):(0,We.jsxs)("button",{type:"button",onClick:()=>J(cn()),disabled:!!E,className:"text-left rounded-lg px-2 py-1.5 -ml-1 min-w-0 max-w-[11rem] sm:max-w-none transition-colors hover:bg-gray-100/90 disabled:opacity-50 disabled:cursor-not-allowed",children:[(0,We.jsx)("span",{className:"block text-sm font-medium text-gray-700",children:"Blank Document"}),(0,We.jsx)("span",{className:"mt-0.5 block text-xs text-gray-500",children:"Start from scratch"})]}):(0,We.jsx)("p",{className:"text-xs text-gray-400",children:"Press \u2318 Enter or Ctrl+Enter to generate"})}),(0,We.jsxs)("div",{className:"flex items-center gap-2 shrink-0",children:[(0,We.jsx)("button",{type:"button",onClick:m,disabled:!!E,className:"px-3 py-1.5 text-sm font-medium text-gray-600 hover:text-gray-800 hover:bg-gray-100/80 rounded-lg transition-colors disabled:opacity-50",children:"Cancel"}),(0,We.jsxs)("button",{type:"button",disabled:!!E,onClick:()=>null===f||void 0===f?void 0:f({signatureBlocksInDraftUnsure:qe}),className:"inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium text-white bg-blue-500 rounded-lg hover:bg-blue-600 disabled:opacity-50 shadow-sm",children:[(0,We.jsx)(ct.A,{className:"w-3.5 h-3.5","aria-hidden":!0}),"Generate document"]})]})]})})]}):An&&Zt>0?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"flex items-center justify-between gap-3 px-5 pt-4 pb-2",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 text-gray-500 min-w-0",children:[(0,We.jsx)(ct.A,{className:"w-4 h-4 text-blue-500/90 shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{className:"text-xs font-medium tracking-wide uppercase",children:"Fill in details"})]}),(0,We.jsx)("button",{type:"button",onClick:m,className:"p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100/80 transition-colors","aria-label":"Close",children:(0,We.jsx)(c.A,{className:"w-4 h-4"})})]}),(0,We.jsxs)("div",{className:"px-5 pb-2 space-y-4 min-h-0 max-h-[min(52vh,28rem)] overflow-y-auto",children:[(0,We.jsxs)("div",{className:"flex items-center gap-3 flex-wrap",children:[(0,We.jsx)("div",{className:"flex items-center gap-1.5","aria-hidden":!0,
1children:Yt.map((e,t)=>(0,We.jsx)("span",{className:"h-2 w-2 rounded-full shrink-0 ".concat(t<En?"bg-blue-500":t===En?"bg-blue-600 ring-2 ring-blue-200":"border border-gray-300 bg-white")},t))}),(0,We.jsxs)("span",{className:"text-sm text-gray-500",children:["Step ",En+1," of ",Zt]})]}),(0,We.jsx)("p",{className:"text-sm text-gray-600",children:rt?"A few specifics help the AI apply your change without guesswork. Skip any question to leave a bracket placeholder where a fact is still missing.":"A few specifics help avoid placeholders. Skip any question to leave a bracket placeholder in the document."}),(0,We.jsxs)("div",{className:nt?"space-y-3":"space-y-3 transition-all duration-150 ease-out motion-reduce:transition-none opacity-100 translate-x-0",children:[(0,We.jsx)("p",{className:"text-[15px] font-semibold text-gray-900 leading-snug",children:Tn}),(()=>{var e;if(!$t)return null;const t="object"===typeof $t&&$t.subtitle?$t.subtitle:"";if("currency"===Xt){var n;const e=null!==(n=Ne[En])&&void 0!==n?n:"";return(0,We.jsxs)("div",{className:"space-y-2",children:[t?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:t}):null,(0,We.jsxs)("div",{className:"flex rounded-lg border border-gray-200/90 bg-white overflow-hidden focus-within:ring-2 focus-within:ring-blue-500/30 focus-within:border-blue-400",children:[(0,We.jsx)("span",{className:"shrink-0 px-3 py-2.5 text-gray-500 text-sm font-medium border-r border-gray-100 bg-gray-50/80",children:"$"}),(0,We.jsx)("input",{ref:Me,id:"create-with-ai-clarify-".concat(En),type:"text",inputMode:"decimal",autoComplete:"off",value:aa(e),onChange:e=>{const t=function(e){let t=String(e).replace(/,/g,"").replace(/[^\d.]/g,"");const n=t.indexOf(".");-1!==n&&(t=t.slice(0,n+1)+t.slice(n+1).replace(/\./g,""));const r=t.split("."),o=(0,a.A)(r,2),i=o[0],s=o[1],l=(i||"").replace(/\D/g,"").slice(0,14),d=void 0!==s?s.replace(/\D/g,"").slice(0,2):void 0;if(void 0!==d){const e=""===l?"0":String(parseInt(l,10));return"".concat(e,".").concat(d)}return""===l?"":String(parseInt(l,10))}(e.target.value);yn(En,t)},className:"flex-1 min-w-0 px-3 py-2.5 text-base text-gray-900 bg-transparent border-0 focus:ring-0 focus:outline-none",placeholder:"0.00"})]}),(0,We.jsx)("p",{className:"text-xs text-gray-400",children:"Amounts in USD."})]})}var r,i;if("email"===Xt)return(0,We.jsxs)("div",{className:"space-y-2",children:[t?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:t}):null,(0,We.jsx)("input",{ref:Me,id:"create-with-ai-clarify-".concat(En),type:"email",autoComplete:"email",value:null!==(r=Ne[En])&&void 0!==r?r:"",onChange:e=>yn(En,e.target.value),className:"w-full text-base text-gray-900 bg-white border border-gray-200/90 rounded-lg px-3 py-2.5 focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 outline-none",placeholder:"[email protected]"})]});if("select"===Xt&&"object"===typeof $t&&Array.isArray($t.options)){var s;const e=$t.options,n=null!==(s=Ne[En])&&void 0!==s?s:"";return(0,We.jsxs)("div",{className:"space-y-2",children:[t?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:t}):null,(0,We.jsx)("div",{className:"flex flex-wrap gap-2",role:"listbox","aria-label":"Choose one",children:e.map((e,t)=>(0,We.jsx)("button",{type:"button",ref:0===t?Me:void 0,onClick:()=>yn(En,e),className:Pn(n===e),children:e},e))})]})}if("date"===Xt){var l;const e=(()=>{const e="preset"===In.mode?In.label:null;if(e&&"Custom"!==e){const t=ra(e,Dn);return t?ta(t):null}if("custom"===In.mode&&Ne["".concat(En,"_iso")]){const e=na(Ne["".concat(En,"_iso")]);return e?ta(e):null}const t=Ne[En];if(!t)return null;const n=/\(([^)]+)\)\s*$/.exec(t);if(n&&"Custom"===n[1]&&Ne["".concat(En,"_iso")]){const e=na(Ne["".concat(En,"_iso")]);return e?ta(e):null}const r=ra(n?n[1]:"",Dn);return r?ta(r):null})();return(0,We.jsxs)("div",{className:"space-y-3",children:[t?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:t}):null,(0,We.jsx)("div",{className:"flex flex-wrap gap-2",children:tn.map((e,t)=>{const n="preset"===In.mode&&In.label===e&&"Custom"!==e,r="Custom"===e&&"custom"===In.mode,a="Custom"===e?r:n;return(0,We.jsx)("button",{type:"button",ref:0===t&&"custom"!==In.mode?Me:void 0,onClick:()=>
1{if("Custom"===e)Le(e=>(0,o.A)((0,o.A)({},e),{},{[En]:{mode:"custom"}})),yn(En,"");else{const t=ra(e,Dn),n=t?"".concat(ta(t)," (").concat(e,")"):e;Le(t=>(0,o.A)((0,o.A)({},t),{},{[En]:{mode:"preset",label:e}})),yn(En,n)}},className:Pn(a),children:e},e)})}),"custom"===In.mode?(0,We.jsxs)("div",{className:"space-y-1",children:[(0,We.jsx)("label",{htmlFor:"create-with-ai-date-".concat(En),className:"sr-only",children:"Custom date"}),(0,We.jsx)("input",{ref:Me,id:"create-with-ai-date-".concat(En),type:"date",value:null!==(l=Ne["".concat(En,"_iso")])&&void 0!==l?l:"",onChange:e=>{const t=e.target.value;Ce(e=>(0,o.A)((0,o.A)({},e),{},{["".concat(En,"_iso")]:t}));const n=na(t);yn(En,n?"".concat(ta(n)," (Custom)"):"")},className:"w-full sm:max-w-xs text-base text-gray-900 bg-white border border-gray-200/90 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 outline-none"})]}):null,e?(0,We.jsxs)("p",{className:"text-sm text-blue-700 font-medium",children:["Due: ",e]}):null]})}return en?(0,We.jsxs)("div",{className:"space-y-2",children:[t?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:t}):null,(0,We.jsx)("textarea",{ref:e=>{ze.current=e,Me.current=e},id:"create-with-ai-clarify-".concat(En),value:null!==(i=Ne[En])&&void 0!==i?i:"",onChange:e=>yn(En,e.target.value),rows:3,placeholder:"Your answer",className:"w-full text-sm text-gray-900 placeholder:text-gray-400 bg-white border border-gray-200/90 rounded-lg px-3 py-2 focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 outline-none resize-y min-h-[5.5rem]"})]}):(0,We.jsxs)("div",{className:"space-y-2",children:[t?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:t}):null,(0,We.jsx)("input",{ref:Me,id:"create-with-ai-clarify-".concat(En),type:"text",value:null!==(e=Ne[En])&&void 0!==e?e:"",onChange:e=>yn(En,e.target.value),className:"w-full text-base text-gray-900 bg-white border border-gray-200/90 rounded-lg px-3 py-2.5 focus:ring-2 focus:ring-blue-500/30 focus:border-blue-400 outline-none",placeholder:"Your answer"})]})})()]},En)]}),(0,We.jsxs)("div",{className:"mt-auto border-t border-gray-100 bg-gray-50/60 rounded-b-[14px] px-5 py-3 space-y-3",children:[(0,We.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[(0,We.jsxs)("button",{type:"button",onClick:fn,className:"inline-flex items-center gap-1 text-sm font-medium text-gray-500 hover:text-gray-700",children:[(0,We.jsx)(Fo.A,{className:"w-3.5 h-3.5","aria-hidden":!0}),"Back"]}),(0,We.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[(0,We.jsx)("button",{type:"button",onClick:hn,disabled:v||D,className:"text-sm font-medium text-gray-500 hover:text-gray-700 disabled:opacity-50 disabled:cursor-not-allowed",children:"Skip this question"}),pn?(0,We.jsxs)("button",{type:"button",onClick:()=>gn(),disabled:v||D,className:"inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium text-white bg-blue-500 rounded-lg hover:bg-blue-600 disabled:opacity-50 shadow-sm",children:[(0,We.jsx)(ct.A,{className:"w-3.5 h-3.5","aria-hidden":!0}),rt?"Update document":"Generate document"]}):(0,We.jsx)("button",{type:"button",onClick:()=>gn(),disabled:v||D,className:"px-3.5 py-1.5 text-sm font-medium text-white bg-blue-500 rounded-lg hover:bg-blue-600 disabled:opacity-50 shadow-sm",children:"Next"})]})]}),(0,We.jsx)("p",{className:"text-xs text-gray-400",children:"text"===Xt&&en||"date"===Xt&&"custom"===In.mode?"Press \u2318 Enter or Ctrl+Enter for Next.":"Press Enter or \u2318 Enter / Ctrl+Enter for Next."})]})]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"flex items-center justify-between gap-3 px-5 pt-4 pb-2",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 text-on-surface min-w-0",children:[(0,We.jsx)(ct.A,{className:"w-4 h-4 text-brand shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{className:"text-sm font-semibold tracking-tight",children:rt?"Update with AI":"Create with AI"})]}),(0,We.jsx)("button",{type:"button",onClick:m,className:"p-1.5 rounded-brand-lg text-on-surface-subtle hover:text-on-surface-muted hover:bg-surface-muted transition-colors","aria-label":"Close",children:(0,We.jsx)(c.A,{className:"w-4 h-4"})})]}),rt?(0,We.jsxs)("div",{className:"px-5 pt-2 space-y-1.5 max-w-full min-w-0 min-h-[2.5rem]",children:[(0,We.jsx)("p",{className:"text-xs font-medium text-on-surface-muted",id:"update-with-ai-suggested-label",children:"Suggested directions"}),"loading"===it||"idle"===it?(0,We.jsxs)("div",{className:"flex items-center gap-2 text-sm text-gray-500 py-0.5",role:"status","aria-live":"polite",children:[(0,We.jsx)(P.A,{className:"w-4 h-4 shrink-0 animate-spin text-gray-400","aria-hidden":!0}),(0,We.jsx)("span",{children:"Reviewing your document\u2026"})]}):null,xt&&"ready"===it?(0,We.jsx)("p",{className:"text-[11px] text-amber-700/90",children:"Couldn't load smart suggestions. Try one of the simple options below, or type your own change."}):null,"ready"===it&&ut.length>0?(0,We.jsx)("ul",{className:"list-none space-y-1.5 m-0 p-0","aria-labelledby":"update-with-ai-suggested-label",children:ut.map(e=>(0,We.jsx)("li",{children:(0,We.jsx)("button",{type:"button",onClick:()=>on(e),className:"w-full text-left text-sm text-gray-600 hover:text-gray-900 underline decoration-gray-200 decoration-dotted underline-offset-2 hover:
1decoration-gray-500 disabled:opacity-50",disabled:!!v,children:e.label})},e.id))}):null]}):null,(0,We.jsxs)("div",{className:"px-5 pt-1 pb-1",children:[(0,We.jsx)("label",{htmlFor:"create-with-ai-prompt",className:"sr-only",children:rt?"What do you want to change?":"What do you need?"}),(0,We.jsxs)("div",{className:"rounded-brand-xl border border-hairline bg-surface-muted/70 px-3 py-2",children:[(0,We.jsxs)("div",{className:"relative",children:[(0,We.jsx)("div",{ref:Ue,"aria-hidden":!0,className:"pointer-events-none absolute inset-0 overflow-hidden px-0 py-2 text-base leading-relaxed whitespace-pre-wrap break-words text-on-surface",style:{minHeight:Jo},children:Qo(X)}),(0,We.jsx)("textarea",{id:"create-with-ai-prompt",ref:_e,value:X,onFocus:()=>zt(!0),onChange:e=>{const t=e.target.value;ee(t),Gt(t,e.target.selectionStart),Qt()},onKeyDown:e=>{if(At){if("Escape"===e.key)return e.stopPropagation(),e.preventDefault(),void Ht();if("ArrowDown"===e.key)return e.preventDefault(),void Lt(e=>Math.min(e+1,Math.max(0,Wt.length-1)));if("ArrowUp"===e.key)return e.preventDefault(),void Lt(e=>Math.max(0,e-1));if("Enter"!==e.key||e.shiftKey)"Tab"===e.key&&Wt.length&&(e.preventDefault(),Kt(Wt[0]));else if(Wt.length){e.preventDefault();const t=Wt[Math.max(0,Math.min(Ft,Wt.length-1))];Kt(t)}}},onSelect:e=>{const t=e.target;t&&"number"===typeof t.selectionStart&&"string"===typeof t.value&&Gt(t.value,t.selectionStart)},onScroll:()=>Qt(),onBlur:()=>{requestAnimationFrame(()=>{document.activeElement!==_e.current&&(Ht(),zt(!1))})},rows:1,placeholder:nn,className:"w-full px-0 py-2 text-base text-transparent caret-on-surface placeholder:text-on-surface-subtle bg-transparent border-0 focus:ring-0 focus:outline-none resize-none leading-relaxed",style:{minHeight:Jo}}),At&&Bt.length>0?(0,We.jsx)("div",{className:"absolute left-0 right-0 top-full z-20 mt-1 max-h-56 overflow-y-auto rounded-brand-xl border border-hairline bg-surface shadow-lg",role:"listbox","aria-label":"Mention a document",onMouseDown:e=>e.preventDefault(),children:Wt.length?(0,We.jsx)("ul",{className:"m-0 list-none divide-y divide-gray-100 p-0",children:Wt.map((e,t)=>{const n=t===Ft;return(0,We.jsx)("li",{children:(0,We.jsx)("button",{type:"button",className:"w-full cursor-pointer px-3 py-2 text-left text-sm ".concat(n?"bg-brand-soft text-brand":"text-on-surface hover:bg-surface-muted"),onMouseEnter:()=>Lt(t),onMouseDown:t=>{t.preventDefault(),Kt(e)},children:(0,We.jsx)("div",{className:"min-w-0 truncate font-medium",children:e.title})})},e.id)})}):(0,We.jsx)("div",{className:"px-3 py-2 text-sm text-on-surface-muted",children:"No matching documents."})}):null]}),Jt?(0,We.jsxs)("p",{className:"mt-2 text-xs text-state-warning",children:[Jt," Every ",(0,We.jsx)("span",{className:"font-medium",children:"@"})," reference must match exactly one document in this workspace (use the @ menu to pick) before you can generate."]}):Mt||At?(0,We.jsxs)("p",{className:"mt-2 text-xs text-on-surface-muted leading-snug",children:["Type ",(0,We.jsx)("span",{className:"font-medium text-on-surface",children:"@"})," to include a workspace document in context."]}):null,!rt&&Vt.pinnedDocumentIds.length>0?(0,We.jsx)("p",{className:"mt-2 text-xs text-on-surface-muted leading-snug",children:"Two-step structured extraction runs when you pin with @ to improve coverage."}):null]})]}),rt||"function"!==typeof J?null:(0,We.jsxs)("div",{className:"px-5 pt-2 pb-1 space-y-2",children:[Sn?(0,We.jsx)("p",{className:"text-xs text-on-surface-muted leading-snug",children:"Add a prompt for AI, or open the PDF in the viewer."}):null,null!==(l=Ye[0])&&void 0!==l&&l.fileName&&!Sn?(0,We.jsxs)("button",{type:"button",onClick:()=>J(cn()),disabled:v||D,className:"inline-flex items-center gap-1.5 max-w-full rounded-brand-lg border border-hairline-strong bg-surface px-3 py-1.5 text-sm font-medium text-on-surface hover:bg-surface-muted transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Use \u201c".concat(Ye[0].fileName,"\u201d as a starting draft"),children:[(0,We.jsx)(R.A,{className:"w-3.5 h-3.5 shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{className:"shrink-0",children:"Use"}),(0,We.jsxs)("span",{className:"truncate",children:["\u201c",Ye[0].fileName,"\u201d"]})]}):null,Sn||null!==(d=Ye[0])&&void 0!==d&&d.fileName?null:(0,We.jsx)("button",{type:"button",onMouseDown:e=>{v||D||(e.preventDefault(),J(cn()))},onClick:e=>{0===e.detail&&(v||D||J(cn()))},disabled:v||D,className:"-mx-2 inline-block rounded-brand-md px-2 py-1.5 text-left text-sm font-medium text-brand hover:bg-brand-soft hover:text-brand-hover hover:underline disabled:opacity-50 disabled:cursor-not-allowed disabled:no-underline",children:"Start blank document"})]}),(0,We.jsx)("div",{className:"px-5 pb-2",children:(0,We.jsxs)("details",{className:"group rounded-brand-xl border border-hairline bg-surface-muted/40 open:bg-surface-muted/60",children:[(0,We.jsxs)("summary",{className:"flex cursor-pointer list-none items-center gap-2 px-3 py-2.5 text-sm font-medium text-on-surface hover:bg-surface-muted/80 rounded-brand-xl transition-colors select-none [&::-webkit-details-marker]:hidden",children:[(0,We.jsx)(A.A,{className:"h-4 w-4 shrink-0 text-on-surface-subtle transition-transform duration-200 group-open:rotate-90","aria-hidden":!0}),"Context & style"]}),(0,We.jsxs)("div",{className:"border-t border-hairline px-3 pt-3 pb-3 space-y-4",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("p",{className:"text-xs font-medium text-on-surface-muted mb-2",children:"Reference PDF (optional)"}),(0,We.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,We.jsx)("input",{ref:Ge,type:"file",accept:"application/pdf,.pdf",className:"hidden",disabled:et||v||D,onChange:ln}),(0,We.jsxs)("button",{type:"button",title:"PDF text only; images omitted for size",disabled:et||v||D||Ye.length>=1,onClick:()=>{var e;return null===(e=Ge.current)||void 0===e?void 0:e.click()},className:"inline-flex items-center gap-1.5 rounded-brand-lg border border-hairline-strong bg-surface px-3 py-1.5 text-xs font-medium text-on-surface hover:bg-surface-muted disabled:opacity-50 disabled:cursor-not-allowed",children:[et?(0,We.jsx)(P.A,{className:"h-3.5 w-3.5 animate-spin shrink-0","aria-hidden":!0}):(0,We.jsx)(xo.A,{className:"h-3.5 w-3.5 shrink-0","aria-hidden":!0}),"Add PDF"]})]}),Ye.length>0?(0,We.jsx)("ul",{className:"mt-2 flex flex-wrap gap-1.5 list-none m-0 p-0",children:Ye.map(e=>(0,We.jsxs)("li",{className:"inline-flex items-center gap-1 rounded-full border border-hairline-strong bg-brand-soft px-2 py-0.5 text-xs text-brand max-w-full",children:[(0,We.jsx)("span",{className:"truncate max-w-[14rem]",title:e.fileName,children:e.fileName}),(0,We.jsx)("button",{type:"button",disabled:et||v||D,onClick:()=>dn(e.id),className:"shrink-0 rounded p-0.5 text-brand hover:bg-surface disabled:opacity-40","aria-label":"Remove ".concat(e.fileName),children:(0,We.jsx)(c.A,{className:"h-3 w-3"})})]},e.id))}):null,(0,We.jsx)("p",{className:"mt-2 text-xs text-on-surface-muted leading-snug",children:"Extracted text is added as context for generation. Images are omitted to save space."})]}),(0,We.jsxs)("div",{className:"flex flex-col sm:flex-row sm:flex-wrap sm:items-center gap-3",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2 min-w-0 sm:max-w-[11rem]",children:[(0,We.jsx)("label",{htmlFor:"create-with-ai-doc-type",className:"text-xs font-medium text-on-surface-muted shrink-0",children:"Type"}),(0,We.jsx)("select",{id:"create-with-ai-doc-type",value:re,onChange:e=>oe(e.target.value),"aria-label":"Document type (optional)",className:"min-w-0 flex-1 text-sm text-on-surface bg-surface border border-hairline rounded-brand-lg px-2 py-1.5 focus:ring-2 focus:ring-focus-ring/30 focus:border-brand outline-none",children:Wo.map(e=>(0,We.jsx)("option",{value:e.value,children:e.label},e.value))})]}),(0,We.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5 min-w-0 flex-1",children:[(0,We.jsx)("span",{className:"text-xs font-medium text-on-surface-muted shrink-0 mr-0.5",children:"Tone"}),(0,We.jsx)("div",{className:"flex flex-wrap gap-1",role:"radiogroup","aria-label":"Tone (optional)",children:Vo.map(e=>(0,We.jsxs)("label",{className:"inline-flex items-center px-2 py-0.5 rounded-full border text-xs cursor-pointer transition-colors ".concat(se===e.value?"border-brand bg-brand-soft text-brand":"border-hairline text-on-surface-muted hover:bg-surface-muted"),children:[(0,We.jsx)("input",{type:"radio",name:"ai-doc-tone",value:e.value,checked:se
1===e.value,onChange:()=>le(e.value),className:"sr-only"}),e.label]},e.value))})]})]}),(0,We.jsxs)("div",{className:"space-y-4 pt-1 border-t border-hairline",children:[(0,We.jsx)("p",{className:"text-xs font-medium text-on-surface-muted",children:"Generation options"}),(0,We.jsxs)("div",{children:[(0,We.jsxs)("label",{className:"flex items-center gap-2 text-xs text-on-surface-muted cursor-pointer select-none",children:[(0,We.jsx)("input",{type:"checkbox",checked:ue,onChange:e=>me(e.target.checked),className:"rounded border-hairline-strong text-brand focus:ring-focus-ring/40 shrink-0"}),(0,We.jsx)("span",{className:"text-on-surface",children:"Include saved profile and contact details"})]}),(0,We.jsx)("p",{className:"mt-1 ml-6 text-xs text-on-surface-muted leading-snug",children:"Uses workspace name, organization, address, phone, and email from your settings\u2014so the draft can use real values instead of placeholders. This is not your document library."})]}),(0,We.jsxs)("div",{children:[(0,We.jsxs)("label",{className:"flex items-center gap-2 text-xs text-on-surface-muted cursor-pointer select-none",children:[(0,We.jsx)("input",{type:"checkbox",checked:ye,onChange:e=>ve(e.target.checked),className:"rounded border-hairline-strong text-brand focus:ring-focus-ring/40 shrink-0"}),(0,We.jsx)("span",{className:"text-on-surface",children:"Search documents for relevant context"})]}),(0,We.jsx)("p",{className:"mt-1 ml-6 text-xs text-on-surface-muted leading-snug",children:"Semantic search over your workspace (same as chat). Refreshes the search index before each generation when this is on."})]}),(0,We.jsxs)("label",{className:"flex items-center gap-2 text-xs text-on-surface-muted cursor-pointer select-none",children:[(0,We.jsx)("input",{type:"checkbox",checked:we,onChange:e=>ke(e.target.checked),className:"rounded border-hairline-strong text-brand focus:ring-focus-ring/40 shrink-0"}),(0,We.jsx)("span",{className:"text-on-surface",children:rt?"Ask for missing details before applying changes":"Ask for missing details before generating"})]})]})]})]})}),(0,We.jsxs)("div",{className:"mt-auto flex items-center justify-between gap-3 px-5 py-3 border-t border-hairline bg-surface-muted/60 rounded-b-[14px]",children:[(0,We.jsx)("div",{className:"min-w-0 flex-1 flex items-center",children:rt?(0,We.jsx)("p",{className:"text-xs text-on-surface-muted",children:"Press \u2318 Enter or Ctrl+Enter to update"}):(0,We.jsx)("p",{className:"text-xs text-on-surface-muted",children:"Press \u2318 Enter or Ctrl+Enter to generate"})}),(0,We.jsxs)("div",{className:"flex items-center gap-2 shrink-0 flex-wrap justify-end",children:[(0,We.jsx)("button",{type:"button",onClick:m,className:"px-3 py-1.5 text-sm font-medium text-on-surface-muted hover:text-on-surface hover:bg-surface-muted rounded-brand-lg transition-colors",children:"Cancel"}),Sn?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("button",{type:"button",onClick:Cn,disabled:!X.trim()||D||qt,className:"inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium rounded-brand-lg border border-hairline-strong bg-surface text-brand hover:bg-brand-soft disabled:opacity-50 disabled:cursor-not-allowed shadow-sm",children:[(0,We.jsx)(ct.A,{className:"w-3.5 h-3.5","aria-hidden":!0}),"Generate with AI"]}),(0,We.jsxs)("button",{type:"button",onClick:()=>{if(v||D||qt)return;const e=cn();e&&"function"===typeof J&&J(e)},disabled:D||qt,className:"inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium text-brand-on bg-brand rounded-brand-lg hover:bg-brand-hover disabled:opacity-50 disabled:cursor-not-allowed shadow-sm",children:[(0,We.jsx)(R.A,{className:"w-3.5 h-3.5","aria-hidden":!0}),"Open"]})]}):(0,We.jsxs)("button",{type:"button",onClick:Cn,disabled:!X.trim()||D||qt||rt&&("loading"===it||"idle"===it),className:"inline-flex items-center gap-1.5 px-3.5 py-1.5 text-sm font-medium text-brand-on bg-brand rounded-brand-lg hover:bg-brand-hover disabled:opacity-50 disabled:cursor-not-allowed shadow-sm",children:[(0,We.jsx)(ct.A,{className:"w-3.5 h-3.5","aria-hidden":!0}),rt?"Update document":"Generate"]})]})]})]}),!D||"clarify"!==b&&"form"!==b?null:(0,We.jsx)("div",{className:"absolute inset-0 z-30 flex items-center justify-center rounded-[14px] bg-white/80 backdrop-blur-[1px]",role:"status","aria-live":"polite",children:(0,We.jsxs)("div",{className:"flex flex-col items-center gap-2 text-sm text-gray-700",children:[(0,We.jsx)(P.A,{className:"w-5 h-5 animate-spin text-blue-600","aria-hidden":!0}),"Checking integrations\u2026"]})})]})]})}),document.body)}async function da(e,t){if(!e)throw new Error("workspaceId is required");const n=Ot(t);return await(0,B.mZ)((0,B.doc)(G.db,"workspaces",e),{documentFolders:n,updatedAt:(0,B.O5)()}),n}async function ca(e,t,n){const r=String(n||"").trim();if(!r)throw new Error("Folder name is required");const o=Ot(t);if(o.some(e=>
1e.name.toLowerCase()===r.toLowerCase()))throw new Error("A folder with that name already exists");const a=function(e){const t=String(e||"").trim();return{id:"folder_".concat(Date.now(),"_").concat(Math.random().toString(36).slice(2,9)),name:t,createdAt:Date.now()}}(r),i=[...o,a];return await da(e,i),{folder:a,folders:i}}async function ua(e,t){if(!e)throw new Error("documentId is required");const n={updatedAt:(0,B.O5)()};n.folderId=null==t||""===t?(0,B.CL)():String(t),await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",e),n)}async function ma(e){const t=Array.isArray(e)?e.filter(Boolean):[];await Promise.all(t.map(e=>ua(e,null)))}var pa=n(55305);function ga(e){return new Promise(t=>setTimeout(t,e))}function ha(e){const t=e&&"object"===typeof e?e.code:null;if(!t||"string"!==typeof t)return!0;return!new Set(["storage/unauthorized","storage/unauthenticated","storage/object-not-found","storage/canceled","storage/invalid-format"]).has(t)}async function fa(e,t,n,r){const o=(0,Ee.c7)(),a=String(r||"document.pdf").replace(/[^\w.\-()+ ]/g,"_"),i="users/".concat(e,"/knowledgeBase/").concat(n,"/").concat(a),s=(0,Ee.KR)(o,t),l=(0,Ee.KR)(o,i),d=await(0,Ee.qW)(s);await(0,Ee.D)(l,d,{contentType:"application/pdf"});const c=await(0,Ee.qk)(l);try{await(0,Ee.XR)(s)}catch(u){}return{url:c,previewUrl:c,storagePath:i}}async function ya(e,t,n,r){let o,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{},i=a.maxAttempts,s=void 0===i?4:i,l=a.initialDelayMs,d=void 0===l?400:l;for(let u=1;u<=s;u++)try{return await fa(e,t,n,r)}catch(c){o=c;if(!(u<s&&ha(c)))throw c;await ga(d*2**(u-1))}throw o}function va(e){let t=e.isOpen,n=e.onClose,r=e.onLeave,o=e.onSave,a=e.isSaving;return t?(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-[100] flex items-center justify-center p-4",children:(0,We.jsx)("div",{className:"bg-white rounded-lg shadow-xl max-w-md w-full",children:(0,We.jsxs)("div",{className:"p-6",children:[(0,We.jsx)("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Unsaved Changes"}),(0,We.jsx)("p",{className:"text-gray-600 mb-6",children:"You have unsaved changes. Are you sure you want to leave without saving?"}),(0,We.jsxs)("div",{className:"flex gap-3 justify-end",children:[(0,We.jsx)("button",{onClick:n,className:"px-4 py-2 text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors",children:"Cancel"}),(0,We.jsx)("button",{onClick:r,className:"px-4 py-2 text-white bg-red-600 rounded-md hover:bg-red-700 transition-colors",children:"Leave Without Saving"}),(0,We.jsx)(St.A,{type:"button",onClick:o,disabled:a,size:"md",className:"px-4 py-2 rounded-md transition-colors ".concat(a?"disabled:!bg-blue-400 disabled:!opacity-100 disabled:!cursor-not-allowed":""),children:a?"Saving...":"Save"})]})]})})}):null}function xa(e){let t=e.isOpen,n=e.validationWarning,r=e.onCancel,o=e.onSaveAnyway;return t&&n?(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-[100] flex items-center justify-center p-4",children:(0,We.jsx)("div",{className:"bg-white rounded-lg shadow-xl max-w-md w-full",children:(0,We.jsxs)("div",{className:"p-6",children:[(0,We.jsx)("h2",{className:"text-xl font-semibold text-gray-900 mb-4",children:"Document Structure Warning"}),(0,We.jsxs)("div",{className:"mb-4",children:[(0,We.jsx)("p",{className:"text-gray-700 mb-3",children:n.warning||"Your document structure will be modified during save."}),n.estimatedChanges&&(0,We.jsx)("div",{className:"bg-yellow-50 border border-yellow-200 rounded-md p-3 mb-3",children:(0,We.jsxs)("p",{className:"text-sm text-yellow-800",children:[(0,We.jsx)("strong",{children:"Expected changes:"})," ",n.estimatedChanges]})}),n.maxDepth&&(0,We.jsxs)("p",{className:"text-sm text-gray-600",children:["Current nesting depth: ",n.maxDepth," levels (safe limit: 15 levels)"]})]}),(0,We.jsxs)("div",{className:"flex gap-3 justify-end",children:[(0,We.jsx)("button",{onClick:r,className:"px-4 py-2 text-gray-700 bg-gray-100 rounded-md hover:bg-gray-200 transition-colors",children:"Cancel"}),(0,We.jsx)("button",{onClick:o,className:"px-4 py-2 text-white bg-yellow-600 rounded-md hover:bg-yellow-700 transition-colors",children:"Save Anyway"})]})]})})}):null}var ba=n(42489),wa=n(26533),ka=n(35327),Aa=n(35746);const ja=e=>{let t=e.workspaceId,n=e.currentUserRole,r=e.onUpdate;const s=(0,i.useState)([]),l=(0,a.A)(s,2),u=l[0],m=l[1],p=(0,i.useState)(!0),g=(0,a.A)(p,2),h=g[0],f=g[1],y=(0,i.useState)(null),v=(0,a.A)(y,2),x=v[0],b=v[1],A=(0,i.useState)(null),j=(0,a.A)(A,2),N=j[0],C=j[1],S=(0,i.useState)(""),E=(0,a.A)(S,2),I=E[0],D=E[1],P=(0,i.useState)("viewer"),T=(0,a.A)(P,2),R=T[0],O=T[1],F=(0,i.useState)(""),L=(0,a.A)(F,2),_=L[0],U=L[1],M=(0,i.useState)(!1),z=(0,a.A)(M,2),B=z[0],V=z[1],J=(0,i.useState)(!1),q=(0,a.A)(J,2),H=q[0],K=q[1],Q=(0,i.useState)(""),Z=(0,a.A)(Q,2),$=Z[0],X=Z[1],ee=(0,i.useState)(!1),te=(0,a.A)(ee,2),ne=te[0],re=te[1],oe={admin:{name:"Admin",icon:ba.A,color:"text-purple-600 bg-purple-50",de
1scription:"Full access including managing members"},editor:{name:"Editor",icon:wa.A,color:"text-green-600 bg-green-50",description:"Can view and edit documents"},viewer:{name:"Viewer",icon:tt.A,color:"text-blue-600 bg-blue-50",description:"Can only view documents"}},ae=(0,i.useCallback)(async e=>{try{const a=[];for(const i of e)try{const e=(0,o.A)({},i),r=i.userId,s=i.name&&"string"===typeof i.name&&(0,Y.NQ)(i.name)||i.email&&"string"===typeof i.email&&(0,Y.NQ)(i.email);let l=null;if(r&&s)try{l=await(0,Y.k5)(r)}catch(t){console.error("\u274c Could not derive key for member:",r,t)}if(l){if(i.name&&"string"===typeof i.name&&(0,Y.NQ)(i.name)){(0,W.gg)("\ud83d\udd13 Attempting to decrypt name:",i.name.substring(0,20)+"...");try{const t=await(0,Y.PV)(i.name,l);t&&(e.name=(0,Y.pM)(t),(0,W.gg)("\u2705 Name decrypted:",e.name))}catch(n){console.error("\u274c Error decrypting name:",n)}}if(i.email&&"string"===typeof i.email&&(0,Y.NQ)(i.email)){(0,W.gg)("\ud83d\udd13 Attempting to decrypt email:",i.email.substring(0,20)+"...");try{const t=await(0,Y.PV)(i.email,l);t&&(e.email=(0,Y.pM)(t),(0,W.gg)("\u2705 Email decrypted:",e.email))}catch(n){console.error("\u274c Error decrypting email:",n)}}}else s&&!r&&console.warn("\u26a0\ufe0f Encrypted member field but no userId; skipping decrypt");if(e.name&&"string"===typeof e.name&&(e.name=(0,Y.pM)(e.name)),e.email&&"string"===typeof e.email&&(e.email=(0,Y.pM)(e.email)),e.name&&!(0,Y.NQ)(e.name)){const t=e.name.split(" ");e.avatar=t.length>1?t[0][0]+t[1][0]:t[0][0],e.avatar=e.avatar.toUpperCase()}else e.email&&!(0,Y.NQ)(e.email)&&(e.avatar=e.email.substring(0,2).toUpperCase());a.push(e)}catch(r){console.error("\u274c Error decrypting user data:",r),a.push(i)}return(0,W.gg)("\u2705 Decryption complete. Decrypted users:",a),a}catch(x){return console.error("\u274c Error in decryptUserData:",x),e}},[]),ie=(0,i.useCallback)(async()=>{try{f(!0),b(null);const e=await(0,Pe.Vr)(t),n=await ae(e);m(n),(0,W.gg)("Loaded workspace members:",n)}catch(e){console.error("Error loading workspace members:",e),b("Failed to load workspace members"),Ie.Ay.error("Failed to load workspace members")}finally{f(!1)}},[ae,t]);(0,i.useEffect)(()=>{t&&ie()},[ie,t]);const se="admin"===n;return h?(0,We.jsxs)("div",{className:"p-4 text-center text-gray-500",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-500 mx-auto mb-2"}),"Loading workspace members..."]}):x?(0,We.jsx)("div",{className:"p-4 text-center text-red-600",children:x}):(0,We.jsxs)("div",{className:"p-4",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,We.jsxs)("h3",{className:"text-lg font-semibold text-gray-900 flex items-center",children:[(0,We.jsx)(k.A,{className:"h-5 w-5 mr-2 text-gray-500"}),"Workspace Access"]}),(0,We.jsxs)("span",{className:"text-sm text-gray-500",children:[u.length," ",1===u.length?"member":"members"]})]}),se&&(0,We.jsx)("div",{className:"mb-5 rounded-lg border border-blue-100 bg-blue-50 p-4",children:(0,We.jsxs)("div",{className:"flex items-start gap-3",children:[(0,We.jsx)("div",{className:"rounded-lg bg-white p-2 text-blue-600",children:(0,We.jsx)(ka.A,{className:"h-4 w-4"})}),(0,We.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,We.jsx)("h4",{className:"text-sm font-semibold text-gray-900",children:"Invite someone to this workspace"}),(0,We.jsx)("p",{className:"mt-1 text-xs text-blue-900",children:"They can be in another organization; this grants access only to this workspace and its synced documents."}),(0,We.jsxs)("form",{onSubmit:async e=>{e.preventDefault();const n=I.split(/[,\n]/).map(e=>e.trim()).filter(Boolean);if(0!==n.length)try{V(!0),b(null),await(0,Pe.nL)(n,R,_,[t],{workspaceOnly:!0}),Ie.Ay.success("Sent ".concat(n.length," workspace invitation").concat(1===n.length?"":"s")),D(""),U(""),X(""),r&&r()}catch(o){console.error("Error sending workspace invite:",o),Ie.Ay.error(o.message||"Failed to send workspace invite")}finally{V(!1)}else Ie.Ay.error("Enter at least one email address")},className:"mt-4 space-y-3",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Email address"}),(0,We.jsx)("textarea",{value:I,onChange:e=>D(e.target.value),rows:2,className:"w-full rounded-md border border-blue-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"[email protected]"}),(0,We.jsx)("p",{className:"mt-1 text-xs text-blue-800",children:"Separate multiple emails with commas or new lines."})]}),(0,We.jsxs)("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-[160px_1fr]",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Access level"}),(0,We.jsx)("select",{value:R,onChange:e=>O(e.target.value),className:"w-full rounded-md border border-blue-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",children:Object.entries(oe).map(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];return(0,We.jsx)("option",{value:n,children:r.name},n)})})]}),(0,We.jsxs)("div",{children:[(0,We.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Message (optional)"}
1),(0,We.jsx)("input",{value:_,onChange:e=>U(e.target.value),className:"w-full rounded-md border border-blue-200 bg-white px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500",placeholder:"Add a note to the invitation"})]})]}),(0,We.jsxs)("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[(0,We.jsx)(St.A,{type:"submit",size:"sm",loading:B,disabled:!I.trim(),leadingIcon:(0,We.jsx)(Aa.A,{className:"h-4 w-4"}),children:"Send invite"}),(0,We.jsxs)("button",{type:"button",onClick:async()=>{try{K(!0),b(null);const e=await(0,Pe.Rp)(R,[t],{workspaceOnly:!0});X(e.url),re(!1),Ie.Ay.success("Workspace invite link created")}catch(e){console.error("Error generating workspace invite link:",e),Ie.Ay.error(e.message||"Failed to create invite link")}finally{K(!1)}},disabled:H,className:"inline-flex items-center justify-center gap-2 rounded-md border border-blue-200 bg-white px-3 py-2 text-sm font-medium text-blue-700 hover:bg-blue-50 disabled:cursor-not-allowed disabled:opacity-50",children:[H?(0,We.jsx)(Se.y$,{size:"sm",className:"text-blue-600","aria-hidden":!0}):(0,We.jsx)(ye.A,{className:"h-4 w-4"}),"Create invite link"]})]})]}),$&&(0,We.jsxs)("div",{className:"mt-3 flex items-center gap-2 rounded-md border border-blue-200 bg-white p-2",children:[(0,We.jsx)("input",{value:$,readOnly:!0,className:"min-w-0 flex-1 bg-transparent px-1 text-xs text-gray-700 focus:outline-none","aria-label":"Workspace invite link"}),(0,We.jsx)("button",{type:"button",onClick:async()=>{try{await navigator.clipboard.writeText($),re(!0),setTimeout(()=>re(!1),2e3)}catch(e){console.error("Failed to copy invite link:",e),Ie.Ay.error("Failed to copy invite link")}},className:"inline-flex h-8 w-8 items-center justify-center rounded-md text-blue-700 hover:bg-blue-50","aria-label":"Copy workspace invite link",children:ne?(0,We.jsx)(d.A,{className:"h-4 w-4 text-green-600"}):(0,We.jsx)(w.A,{className:"h-4 w-4"})})]})]})]})}),0===u.length?(0,We.jsxs)("div",{className:"text-center py-8 text-gray-500",children:[(0,We.jsx)(k.A,{className:"h-12 w-12 mx-auto mb-2 text-gray-400"}),(0,We.jsx)("p",{children:"No members found"})]}):(0,We.jsx)("div",{className:"space-y-2",children:u.map(e=>{var n,o,a,i;const s=(null===(n=oe[e.workspaceRole])||void 0===n?void 0:n.icon)||tt.A,l=oe[e.workspaceRole]||oe.viewer,d=e.userId===(null===G.j2||void 0===G.j2||null===(o=G.j2.currentUser)||void 0===o?void 0:o.uid);return(0,We.jsx)("div",{className:"flex items-center justify-between p-3 bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors",children:(0,We.jsxs)("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[(0,We.jsx)("div",{className:"flex-shrink-0",children:e.avatar?(0,We.jsx)("div",{className:"w-10 h-10 rounded-full bg-blue-500 flex items-center justify-center text-white font-medium",children:e.avatar}):(0,We.jsx)("div",{className:"w-10 h-10 rounded-full bg-gray-300 flex items-center justify-center text-gray-600 font-medium",children:(null===(a=e.name)||void 0===a||null===(i=a[0])||void 0===i?void 0:i.toUpperCase())||"?"})}),(0,We.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,We.jsx)("p",{className:"text-sm font-medium text-gray-900 truncate",children:e.name||"Unknown User"}),(0,We.jsx)("p",{className:"text-xs text-gray-500 truncate",children:e.email||"No email"})]}),(0,We.jsx)("div",{className:"flex items-center space-x-2 flex-shrink-0",children:N===e.userId?(0,We.jsx)("select",{value:e.workspaceRole||"viewer",onChange:n=>(async(e,n)=>{try{await(0,Pe.aI)(t,e,n),Ie.Ay.success("User role updated"),C(null),ie(),r&&r()}catch(o){console.error("Error updating role:",o),Ie.Ay.error(o.message||"Failed to update role")}})(e.userId,n.target.value),onBlur:()=>C(null),className:"text-xs border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-blue-500",autoFocus:!0,children:Object.keys(oe).map(e=>(0,We.jsx)("option",{value:e,children:oe[e].name},e))}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"flex items-center space-x-1 px-2 py-1 rounded-full text-xs font-medium ".concat(l.color),children:[(0,We.jsx)(s,{className:"h-3 w-3"}),(0,We.jsx)("span",{children:l.name})]}),se&&!d&&(0,We.jsx)("button",{onClick:()=>C(e.userId),className:"text-xs text-blue-600 hover:text-blue-700",title:"Change role",children:"Edit"})]})}),se&&!d&&(0,We.jsx)("button",{onClick:()=>(async(e,n)=>{if(window.confirm("Are you sure you want to remove ".concat(n||"this user"," from this workspace?")))try{await(0,Pe.hH)(t,e),Ie.Ay.success("User removed from workspace"),ie(),r&&r()}catch(o){console.error("Error removing user:",o),Ie.Ay.error(o.message||"Failed to remove user")}})(e.userId,e.name),className:"ml-2 text-red-600 hover:text-red-700 flex-shrink-0",title:"Remove from workspace",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]})},e.userId)})}),!se&&(0,We.jsx)("div",{className:"mt-4 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:(0,We.jsx)("p",{className:"text-xs text-blue-700",children:"Only workspace admins can manage member access. Contact your workspace admin to request changes."})})]})};function Na(e){let t=e.isOpen,n=e.workspaceId,r=e.workspaceName,o=e.currentUserRole,a=e.organizationId,i=void 0===a?null:a,s=e.onClose;return t?(0,We.jsx)("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-black bg-opacity-50",children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between p-4 border-b border-gray-200",children:[(0,We.jsxs)("h2",{className:"text-xl font-semibold text-gray-900",children:["Workspace Access - ",r]}),(0,We.jsx)("button",{onClick:s,className:"text-gray-400 hover:text-gray-600",children:(0,We.jsx)(c.A,{className:"h-6 w-6"})})]}),(0,We.jsx)("div",{className:"flex-1 overflow-y-auto p-4",children:(0,We.jsx)(ja,{workspaceId:n,workspaceName:r,organizationId:i,currentUserRole:o,onUp
1date:()=>{window.dispatchEvent(new CustomEvent("workspacesUpdated"))}})})]})}):null}var Ca=n(17070);function Sa(e,t){const n=(0,i.useState)(void 0),r=(0,a.A)(n,2),o=r[0],s=r[1],l=(0,i.useState)(null),d=(0,a.A)(l,2),c=d[0],u=d[1],m=(0,i.useState)(Boolean(e||t)),p=(0,a.A)(m,2),g=p[0],h=p[1];(0,i.useEffect)(()=>{if(!e)return void s(void 0);const t=(0,B.doc)(G.db,"organizations",e);let n=!1;const r=(0,B.aQ)(t,e=>{var r;const o=e.exists()?e.data():null,a=null===o||void 0===o||null===(r=o.settings)||void 0===r?void 0:r.categoryPresets;s(a),n||!e.exists()||(0,Ca.P6)(a)||(n=!0,(0,B.mZ)(t,{"settings.categoryPresets":[...Ca.MT]}).catch(e=>{console.warn("useCategoryPresets backfill skipped:",(null===e||void 0===e?void 0:e.code)||(null===e||void 0===e?void 0:e.message)||e)}))},e=>{console.error("useCategoryPresets org snapshot:",e),s(void 0)});return()=>r()},[e]),(0,i.useEffect)(()=>{if(!t||"global"===t)return u(null),void h(!1);h(!0);const e=(0,B.doc)(G.db,"workspaces",t),n=(0,B.aQ)(e,e=>{const t=e.exists()?e.data():null,n=null===t||void 0===t?void 0:t.categoryPresetsOverride;u(Array.isArray(n)?n:null),h(!1)},e=>{console.error("useCategoryPresets workspace snapshot:",e),u(null),h(!1)});return()=>n()},[t]);const f=(0,i.useMemo)(()=>(0,Ca.co)(o),[o]),y=(0,i.useMemo)(()=>(0,Ca.RW)({orgPresetsRaw:o,workspaceOverride:c}),[o,c]),v=(0,Ca.C1)(c);return{presets:y,orgPresets:f,orgPresetsRaw:o,workspaceOverride:c,usingWorkspaceOverride:v,loading:g}}const Ea=(0,i.lazy)(()=>Promise.all([n.e(8706),n.e(1062)]).then(n.bind(n,1062)));function Ia(e){let t=e.isOpen,n=e.currentWorkspaceObject,r=(e.currentWorkspace,e.sidebarFilteredDocs),o=e.onClose,a=e.userProfile,s=e.activeDocumentId,l=void 0===s?null:s;return n?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"fixed right-0 top-0 h-screen w-full sm:w-96 bg-white shadow-lg transform transition-transform duration-300 z-50 flex flex-col ".concat(t?"translate-x-0":"translate-x-full"),onClick:e=>e.stopPropagation(),children:[(0,We.jsxs)("div",{className:"h-[72px] flex items-center justify-between px-3 border-b border-gray-200 bg-gray-50 flex-shrink-0",children:[(0,We.jsxs)("div",{className:"min-w-0 overflow-hidden",children:[(0,We.jsx)("h2",{className:"text-lg font-semibold text-gray-900 m-0 leading-snug truncate",children:"AI Assistant"}),(0,We.jsx)("p",{className:"text-sm text-gray-500 m-0 truncate",children:n.name})]}),(0,We.jsx)("button",{onClick:o,className:"p-2 hover:bg-gray-200 rounded-md transition-colors",children:(0,We.jsx)(c.A,{className:"w-5 h-5 text-gray-500"})})]}),(0,We.jsx)("div",{className:"flex-1 min-h-0",children:t?(0,We.jsx)(i.Suspense,{fallback:(0,We.jsx)("div",{className:"flex items-center justify-center py-16",children:(0,We.jsx)(Se.y$,{size:"lg",className:"text-blue-600"})}),children:(0,We.jsx)(Ea,{workspace:n,filteredDocuments:r,userProfile:a,activeDocumentId:l,onAgentReady:e=>{(0,W.gg)("\u2705 Agent ready:",e)}})}):(0,We.jsx)("div",{className:"p-4",children:(0,We.jsx)("p",{className:"text-sm text-gray-500",children:"Sidebar closed"})})})]}),t&&(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-40 lg:hidden",onClick:o})]}):null}function Da(e){let t=e.expandedCategories,n=e.toggleCategory,r=e.documents,o=e.currentPage,i=e.onDocumentClick;if(!r||!Array.isArray(r))return(0,We.jsx)("div",{className:"px-2 py-2 text-sm text-gray-500",children:"No documents available"});const s={};r.forEach(e=>{const t=e.category||"Uncategorized";s[t]||(s[t]=[]),s[t].push(e)});const l=Object.entries(s).sort((e,t)=>{let n=(0,a.A)(e,1)[0],r=(0,a.A)(t,1)[0];return n.localeCompare(r,void 0,{sensitivity:"base"})});return(0,We.jsx)(We.Fragment,{children:l.map(e=>{let r=(0,a.A)(e,2),s=r[0],l=r[1];return(0,We.jsxs)("div",{className:"mt-1",children:[(0,We.jsxs)("button",{onClick:()=>n(s),className:"flex items-center w-full px-2 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md",children:[t[s]?(0,We.jsx)(y.A,{className:"h-4 w-4 mr-1.5 flex-shrink-0"}):(0,We.jsx)(A.A,{className:"h-4 w-4 mr-1.5 flex-shrink-0"}),(0,We.jsx)("span",{className:"truncate",children:s})]}),t[s]&&(0,We.jsx)("div",{className:"pl-6 space-y-1 mt-1",children:l.map(e=>(0,We.jsxs)("a",{href:"#",className:"flex items-center px-2 py-1.5 text-sm ".concat(o===e.id?"text-blue-600 bg-blue-50 hover:bg-blue-100":"text-gray-600 hover:bg-gray-100"," rounded-md"),onClick:t=>{t.preventDefault(),i(e.id)},children:["image"===e.type?(0,We.jsx)(fe.A,{className:"w-4 h-4 mr-1.5 text-gray-400 flex-shrink-0"}):(0,We.jsx)(R.A,{className:"w-4 h-4 mr-1.5 text-gray-400 flex-shrink-0"}),(0,We.jsx)("span",{className:"truncate",children:(0,_e.Od)(e,"Untitled")})]},e.id))})]},s)})})}function Pa(e){let t=e.currentWorkspace,n=e.allDocuments,r=e.showFavorites,o=e.favoriteDocuments,s=e.favoritesLoading,l=e.expandedCategories,d=e.toggleCategory,c=e.currentPage,u=e.onDocumentClick,m=e.onReorder,p=e.categoryOrder,g=e.onCategoryReorder;
1const h=(0,i.useState)(null),f=(0,a.A)(h,2),v=f[0],x=f[1],b=(0,i.useState)(null),w=(0,a.A)(b,2),k=w[0],j=w[1];let N=null;t&&("string"===typeof t?N=t:"object"===typeof t&&null!==t&&(N=t.id||t._id||t.workspaceId));const C=N?n.filter(e=>!!Array.isArray(e.workspaceIds)&&e.workspaceIds.some(e=>String(e)===String(N))):n,S=(0,io.b4)(C);if(r){const e=(0,io.b4)(o);return(0,We.jsx)("div",{className:"mt-1",children:s?(0,We.jsx)("div",{className:"px-2 py-2 text-sm text-gray-500",children:"Loading favorites..."}):0===o.length?(0,We.jsx)("div",{className:"px-2 py-2 text-sm text-gray-500",children:"No favorites yet"}):Object.entries(e.categories).map(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];const o=(null===r||void 0===r?void 0:r.subcategories)||{};return(0,We.jsxs)("div",{className:"mt-1",children:[(0,We.jsxs)("button",{onClick:()=>d(n),className:"flex items-center w-full px-2 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md",children:[l[n]?(0,We.jsx)(y.A,{className:"h-4 w-4 mr-1.5"}):(0,We.jsx)(A.A,{className:"h-4 w-4 mr-1.5"}),n]}),l[n]&&(0,We.jsx)("div",{className:"pl-6 mt-1 space-y-1",children:Object.entries(o).map(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];return(0,We.jsx)("div",{children:Array.isArray(r)&&r.map(e=>(0,We.jsxs)("a",{href:"#",className:"flex items-center px-2 py-1.5 text-sm ".concat(c===e.id?"text-blue-600 bg-blue-50 hover:bg-blue-100":"text-gray-600 hover:bg-gray-100"," rounded-md"),onClick:t=>{t.preventDefault(),u(e.id)},children:[(0,We.jsx)("span",{className:"w-4 h-4 flex items-center justify-center mr-1.5 flex-shrink-0",children:"image"===e.type?(0,We.jsx)(fe.A,{className:"w-4 h-4 text-gray-400"}):(0,We.jsx)(R.A,{className:"w-4 h-4 text-gray-400"})}),(0,_e.Od)(e,"Untitled")]},e.id))},n)})})]},n)})})}if(!S||!S.categories||0===Object.keys(S.categories).length)return(0,We.jsx)(Da,{expandedCategories:l,toggleCategory:d,documents:C,currentPage:c,onDocumentClick:u});const E=function(e,t){if(!t||!Array.isArray(t)||0===t.length)return e;const n=new Map(e),r=[];t.forEach(e=>{n.has(e)&&(r.push([e,n.get(e)]),n.delete(e))});const o=[...n.entries()].sort((e,t)=>{let n=(0,a.A)(e,1)[0],r=(0,a.A)(t,1)[0];return n.localeCompare(r,void 0,{sensitivity:"base"})});return[...r,...o]}(Object.entries(S.categories),p),I=[];E.forEach(e=>{let t=(0,a.A)(e,2)[1];const n=(null===t||void 0===t?void 0:t.subcategories)||{};Object.values(n).forEach(e=>{Array.isArray(e)&&e.forEach(e=>I.push(e.id))})});const D=!!g,P=E.map(e=>(0,a.A)(e,1)[0]),T=()=>{x(null),j(null)};return(0,We.jsx)("div",{children:E.map(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];const o=(null===r||void 0===r?void 0:r.subcategories)||{},i=v===n,s=k===n&&v!==n;return(0,We.jsxs)("div",{className:"mt-1 transition-colors ".concat(s?"border-t-2 border-blue-400":"border-t-2 border-transparent"),onDragOver:D?e=>((e,t)=>{e.dataTransfer.types.includes("text/x-category")&&(e.preventDefault(),e.dataTransfer.dropEffect="move",k!==t&&j(t))})(e,n):void 0,onDrop:D?e=>((e,t)=>{e.preventDefault();const n=e.dataTransfer.getData("text/x-category");if(x(null),j(null),!n||n===t)return;const r=P.filter(e=>e!==n),o=r.indexOf(t);o>=0?r.splice(o,0,n):r.push(n),g(r)})(e,n):void 0,onDragLeave:D?()=>{k===n&&j(null)}:void 0,children:[(0,We.jsxs)("div",{className:"flex items-center w-full px-2 py-1.5 text-sm font-medium text-gray-700 hover:bg-gray-100 rounded-md group ".concat(i?"opacity-30":""),children:[D&&(0,We.jsx)("div",{draggable:!0,onDragStart:e=>{e.stopPropagation(),((e,t)=>{e.dataTransfer.setData("text/x-category",t),e.dataTransfer.effectAllowed="move",x(t)})(e,n)},onDragEnd:T,className:"opacity-0 group-hover:opacity-100 transition-opacity cursor-grab active:cursor-grabbing mr-0.5 flex-shrink-0",children:(0,We.jsx)(Tt.A,{className:"h-3.5 w-3.5 text-gray-400"})}),(0,We.jsxs)("button",{onClick:()=>d(n),className:"flex items-center flex-1 min-w-0",children:[l[n]?(0,We.jsx)(y.A,{className:"h-4 w-4 mr-1.5 flex-shrink-0"}):(0,We.jsx)(A.A,{className:"h-4 w-4 mr-1.5 flex-shrink-0"}),(0,We.jsx)("span",{className:"truncate",children:n})]})]}),l[n]&&(0,We.jsx)("div",{className:"pl-6 mt-1 space-y-1",children:Object.entries(o).map(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];return(0,We.jsx)("div",{children:Array.isArray(r)&&r.map(e=>(0,We.jsxs)("a",{href:"#",draggable:!!m,onDragStart:m?t=>{t.dataTransfer.setData("docId",e.id),t.dataTransfer.effectAllowed="move"}:void 0,onDragOver:m?e=>{e.preventDefault(),e.dataTransfer.dropEffect="move"}:void 0,onDrop:m?t=>{t.preventDefault();const n=t.dataTransfer.getData("docId"),r=e.id;if(!n||n===r)return;const o=I.filter(e=>e!==n),a=o.indexOf(r);a>=0?o.splice(a,0,n):o.push(n),m(o)}:void 0,className:"flex items-center px-2 py-1.5 text-sm ".concat(c===e.id?"text-blue-600 bg-blue-50 hover:bg-blue-100":"text-gray-600 hover:bg-gray-100"," rounded-md ").concat(m?"cursor-grab active:cursor-grabbing":""),onClick:t=>{t.preventDefault(),u(e.id)},children:[(0,We.jsx)("span",{className:"w-4 h-4 flex items-center justify-center mr-1.5 flex-shrink-0",children:(0,We.jsx)(R.A,{className:"w-4 h-4 text-gray-400"})}),(0,_e.Od)(e,"Untitled")]},e.id))},n)})})]},n)})})}var Ta=n(51884),Ra=n(53639),Oa=n(37916),Fa=n(46963),La=n(97666),_a=n(44646),Ua=n(86376),Ma=n(81990),za=n(9493),Ba=n(95264);const Wa=e=>{let t=e.currentOrganizationId,r=e.onOrganizationChange;const o=(0,i.useState)([]),s=(0,a.A)(o,2),l=s[0],c=s[1],u=(0,i.useState)(!0),m=(0,a.A)(u,2),p=m[0],g=m[1],h=(0,i.useState)(!1),f=(0,a.A)(h,2),v=f[0],x=f[1],b=(0,i.useState)(null),w=(0,a.A)(b,2),k=w[0],A=w[1],j=(0,i.useState)(null),N=(0,a.A)(j,2),C=N[0],S=N[1],E=(0,i.useCallback)(async()=>{try{g(!0),(0,W.gg)("\ud83d\udd04 Loading organizations...");const e=new Promise((e,t)=>
1setTimeout(()=>t(new Error("Timeout loading organizations")),1e4)),t=await Promise.race([(0,Pe.wV)(),e]);(0,W.gg)("\u2705 Loaded organizations:",t),c(t||[]),t&&0!==t.length||(0,W.gg)("\u26a0\ufe0f No organizations found for user")}catch(e){console.error("\u274c Error loading organizations:",e),(0,W.gg)("\u274c Error loading organizations:",e),"permission-denied"===e.code||!e.message||e.message.includes("not a member")||e.message.includes("Timeout")||Ie.Ay.error("Failed to load organizations"),c([])}finally{g(!1)}},[]);(0,i.useEffect)(()=>{const e=()=>{const e=(0,Pe.getSelectedOrganizationId)(),n=e||t;S(n),(0,W.gg)("OrganizationSwitcher - Active org ID:",n,"from localStorage:",e,"from prop:",t)};e();const n=()=>{e(),E()};return window.addEventListener("organizationChanged",n),E(),()=>window.removeEventListener("organizationChanged",n)},[t,E]),(0,i.useEffect)(()=>{const e=C||t;if(e&&l.length>0){const t=l.find(t=>t.id===e);t&&A(t.name)}else if(e&&0===l.length&&!p){(async()=>{try{const t=(await Promise.resolve().then(n.bind(n,47081))).getUserOrganizationData,r=await t(e);r&&A(r.name)}catch(t){console.error("Error fetching org name:",t)}})()}},[C,t,l,p]);const I=C||t,D=l.find(e=>e.id===I);if(p)return(0,We.jsx)("div",{className:"px-4 py-2 text-sm text-gray-500",children:"Loading organizations..."});if(0===l.length&&(t||C)){return k?(0,We.jsxs)("div",{className:"flex items-center text-sm text-gray-700",children:[(0,We.jsx)(Ba.A,{className:"h-4 w-4 text-gray-400 mr-3 flex-shrink-0"}),(0,We.jsx)("span",{className:"font-medium truncate",children:k})]}):(0,We.jsx)("div",{className:"px-4 py-2 text-sm text-gray-500",children:"Loading organization..."})}if(l.length<=1){const e=D||(1===l.length?l[0]:null),n=(null===e||void 0===e?void 0:e.name)||k||"Organization",r=(null===e||void 0===e?void 0:e.role)||"";return e||k||t?(0,We.jsxs)("div",{className:"flex items-center text-sm text-gray-700",children:[(0,We.jsx)(Ba.A,{className:"h-4 w-4 text-gray-400 mr-3 flex-shrink-0"}),(0,We.jsx)("span",{className:"font-medium truncate",children:n}),r&&(0,We.jsxs)("span",{className:"text-xs text-gray-500 capitalize ml-1",children:["(",r,")"]})]}):null}return(0,We.jsxs)("div",{className:"relative",children:[(0,We.jsxs)("button",{onClick:()=>x(!v),className:"w-full flex items-center justify-between px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 rounded-md transition-colors",children:[(0,We.jsxs)("div",{className:"flex items-center space-x-2 min-w-0",children:[(0,We.jsx)(Ba.A,{className:"h-4 w-4 text-gray-500 flex-shrink-0"}),(0,We.jsx)("span",{className:"truncate",children:(null===D||void 0===D?void 0:D.name)||k||"Select Organization"}),(D||k)&&(0,We.jsxs)("span",{className:"text-xs text-gray-500 capitalize",children:["(",(null===D||void 0===D?void 0:D.role)||"",")"]})]}),(0,We.jsx)(y.A,{className:"h-4 w-4 text-gray-400 transition-transform ".concat(v?"transform rotate-180":"")})]}),v&&(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("div",{className:"fixed inset-0 z-10",onClick:()=>x(!1)}),(0,We.jsx)("div",{className:"absolute left-0 mt-1 w-64 bg-white rounded-md shadow-lg border border-gray-200 z-20 max-h-64 overflow-y-auto",children:(0,We.jsx)("div",{className:"py-1",children:l.map(e=>{const n=e.id===I;return(0,We.jsxs)("button",{onClick:()=>(async e=>{const n=C||t;if(e===n)return void x(!1);const o=l.find(t=>t.id===e);(0,W.gg)("[OrgSwitch] Switch initiated: from=".concat(n," to=").concat(e," name=").concat(null===o||void 0===o?void 0:o.name));try{(0,Pe.t6)(e),S(e),r&&r(e,(null===o||void 0===o?void 0:o.name)||"organization"),x(!1),Ie.Ay.success("Organization switched")}catch(a){console.error("Error switching organization:",a),Ie.Ay.error("Failed to switch organization")}})(e.id),className:"w-full flex items-center justify-between px-4 py-2 text-sm text-left hover:bg-gray-50 transition-colors ".concat(n?"bg-blue-50":""),children:[(0,We.jsxs)("div",{className:"flex items-center space-x-2 min-w-0 flex-1",children:[(0,We.jsx)(Ba.A,{className:"h-4 w-4 text-gray-500 flex-shrink-0"}),(0,We.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,We.jsx)("div",{className:"truncate font-medium text-gray-900",children:e.name}),(0,We.jsx)("div",{className:"text-xs text-gray-500 capitalize",children:e.role})]})]}),n&&(0,We.jsx)(d.A,{className:"h-4 w-4 text-blue-600 flex-shrink-0"})]},e.id)})})})]})]})};function Va(e){var t,n;let r=e.userProfile,o=e.profileMenuOpen,s=e.setProfileMenuOpen,l=e.currentOrganizationId,d=e.organizationId,c=e.setCurrentOrganizationId,u=e.setOrganizationId,m=e.currentUserRole,p=e.hasUnseenUpdates,g=e.appUpdatesVersion,h=e.appUpdatesIsBeta,f=e.onShowWhatsNew,v=e.onLogout,x=e.profileMenuRef,b=e.resetViewOnOrgSwitch,w=e.disableMenu,k=void 0!==w&&w,A=e.showExportData,j=void 0!==A&&A,N=e.onExportData;const C=(0,i.useState)(!1),S=(0,a.A)(C,2),E=S[0],I=S[1],D=(0,i.useState)(!1),P=(0,a.A)(D,2),T=P[0],R=P[1],O=null===r||void 0===r?void 0:r.profileImageUrl,F=l||d;(0,i.useEffect)(()=>{I(!1)},[O]),(0,i.useEffect)(()=>{let e=!1;return"admin"===m&&F?((0,Pe.getUserOrganizationData)(F).then(t=>{e||R("partner"===(null===t||void 0===t?void 0:t.type))}).catch(t=>{(0,W.gg)("Unable to load organization partner status:",t),e||R(!1)}),()=>{e=!0}):(R(!1),()=>{e=!0})}
1,[m,F]);const L=!O||E,_="".concat((null===(t=((null===r||void 0===r?void 0:r.firstName)||"").replace(/['"]/g,""))||void 0===t?void 0:t[0])||"").concat((null===(n=((null===r||void 0===r?void 0:r.lastName)||"").replace(/['"]/g,""))||void 0===n?void 0:n[0])||"");return(0,We.jsxs)("div",{className:"relative",ref:x,children:[(0,We.jsxs)("button",{onClick:()=>{k||s(!o)},type:"button","aria-haspopup":k?void 0:"menu","aria-expanded":k?void 0:Boolean(o),"aria-label":"Profile menu",className:"flex items-center gap-2 px-3 py-2 rounded-md transition-colors ".concat(k?"cursor-default":"hover:bg-gray-100"),children:[L?(0,We.jsx)("div",{className:"w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white text-sm font-semibold flex-shrink-0",children:_}):(0,We.jsx)("div",{className:"w-8 h-8 rounded-full overflow-hidden flex-shrink-0",children:(0,We.jsx)("img",{src:O,alt:"Profile",className:"w-full h-full object-cover",crossOrigin:"anonymous",referrerPolicy:"no-referrer",onError:()=>{(0,W.gg)("Profile image failed to load:",O),I(!0)},onLoad:()=>{(0,W.gg)("Profile image loaded successfully")}},O)}),(0,We.jsx)("span",{className:"hidden md:block text-sm font-medium text-gray-700 truncate max-w-32",children:"".concat(((null===r||void 0===r?void 0:r.firstName)||"").replace(/['"]/g,"")," ").concat(((null===r||void 0===r?void 0:r.lastName)||"").replace(/['"]/g,"")).trim()||((null===r||void 0===r?void 0:r.email)||"").replace(/['"]/g,"")||"User"}),!k&&(0,We.jsx)(y.A,{className:"h-4 w-4 text-gray-500 transition-transform flex-shrink-0 ".concat(o?"transform rotate-180":"")})]}),!k&&o&&(0,We.jsx)("div",{className:"absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-70",style:{zIndex:"100"},children:(0,We.jsxs)("div",{className:"py-1",children:[(0,We.jsxs)("div",{className:"px-4 py-3 border-b border-gray-100",children:[(0,We.jsx)("p",{className:"text-sm font-medium text-gray-900 truncate",children:"".concat(((null===r||void 0===r?void 0:r.firstName)||"").replace(/['"]/g,"")," ").concat(((null===r||void 0===r?void 0:r.lastName)||"").replace(/['"]/g,"")).trim()||"User"}),(0,We.jsx)("p",{className:"text-sm text-gray-500 truncate",children:((null===r||void 0===r?void 0:r.email)||"").replace(/['"]/g,"")})]}),(l||d)&&(0,We.jsx)("div",{className:"px-4 py-2",children:(0,We.jsx)(Wa,{currentOrganizationId:l||d,onOrganizationChange:(e,t)=>
1{(0,W.gg)("[OrgSwitch] ProfileMenu.onOrganizationChange: setting both IDs to ".concat(e," (").concat(t,"), previous current=").concat(l," org=").concat(d)),c(e),u(e),s(!1),"function"===typeof b&&b(t)}})}),(0,We.jsxs)("a",{href:"/profile",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(Ae.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Profile Settings"]}),"admin"===m&&(0,We.jsxs)(z.N_,{to:"/invite",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(Ta.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Invite Users"]}),"admin"===m&&T&&(0,We.jsxs)(z.N_,{to:"/partner",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(Ra.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Partner Console"]}),(0,We.jsxs)("a",{href:"/integrations",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(Oa.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Based Abilities"]}),(0,We.jsxs)("button",{onClick:()=>{f(),s(!1)},className:"w-full text-left flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors relative",children:[(0,We.jsx)(ct.A,{className:"mr-3 h-4 w-4 text-gray-400"}),(0,We.jsxs)("span",{className:"flex items-center gap-2",children:["What's New",p&&(0,We.jsx)("span",{className:"w-2 h-2 bg-red-500 rounded-full"})]})]}),(0,We.jsxs)("a",{href:Te.w,target:"_blank",rel:"noopener noreferrer",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(Fa.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"iOS app"]}),(0,We.jsxs)("a",{href:{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_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #69 from grigerny/cursor/native-document-tables-6648\n\nNative document tables for editor and MCP agents",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_6MQChUZTeZEjuh9PAEPmwanHsu8y",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"fe8e0cad17d5c751081fbff8964f57a16f15178c",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-o7e1bdtta-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_HELP_CENTER_URL||"https://trybased.com/shared/based-help-center",target:"_blank",rel:"noopener noreferrer",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(La.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Help"]}),(0,We.jsxs)("a",{href:({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_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"}
1,"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #69 from grigerny/cursor/native-document-tables-6648\n\nNative document tables for editor and MCP agents",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_6MQChUZTeZEjuh9PAEPmwanHsu8y",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"fe8e0cad17d5c751081fbff8964f57a16f15178c",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-o7e1bdtta-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_HELP_CENTER_URL||"https://trybased.com/shared/based-help-center")+"#section-contact-us",target:"_blank",rel:"noopener noreferrer",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(ka.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Contact Us"]}),(0,We.jsxs)(z.N_,{to:"/feedback",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(_a.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Feature requests & bugs"]}),"admin"===m&&(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("div",{className:"border-t border-gray-100 my-1"}),(0,We.jsxs)("a",{href:"/billing",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(Ua.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Billing & Plans"]})]}),"[email protected]"===((null===r||void 0===r?void 0:r.email)||"").toLowerCase().trim()&&(0,We.jsxs)("a",{href:"/admin",className:"flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 transition-colors",onClick:()=>s(!1),children:[(0,We.jsx)(ba.A,{className:"mr-3 h-4 w-4 text-gray-400"}),"Admin Dashboard"]}),(0,We.jsxs)("div",{className:"border-t border-gray-100 mt-1 pt-1",children:[j&&"function"===typeof N&&(0,We.jsx)("div",{className:"px-3 py-2",children:(0,We.jsxs)("button",{type:"button",onClick:()=>{N(),s(!1)},className:"w-full flex items-center justify-center gap-2 rounded-md border-2 border-red-500 bg-red-50 px-3 py-2.5 text-sm font-semibold text-red-700 hover:bg-red-100 transition-colors shadow-sm",children:[(0,We.jsx)(Ma.A,{className:"h-4 w-4 text-red-600"}),"Export data"]})}),(0,We.jsxs)("div",{className:"flex items-center px-4 py-2 text-xs text-gray-500 select-none",children:[(0,We.jsx)("span",{children:"Current Beta version"}),(0,We.jsxs)("span",{className:"ml-auto font-mono text-gray-600",children:[g?"v".concat(g):"\u2014",g&&!h?" (not beta)":""]})]}),(0,We.jsxs)("button",{onClick:v,className:"w-full text-left flex items-center px-4 py-2 text-sm text-red-700 hover:bg-red-50 transition-colors",children:[(0,We.jsx)(za.A,{className:"mr-3 h-4 w-4 text-red-400"}),"Sign out"]})]})]})})]})}var Ja=n(76833),qa=n(77819);const Ha=new Set(["queued","running"]);function Ga(e){if(null===e||void 0===e||!e.progress)return null;const t=e.progress,n=t.message,r=t.documentsDone,o=void 0===r?0:r,a=t.documentsTotal,i=void 0===a?0:a,s=t.workspacesDone,l=void 0===s?0:s,d=t.workspacesTotal,c=void 0===d?0:d;return[n,i>0?"".concat(o,"/").concat(i," documents"):o>0?"".concat(o," documents"):null,c>1?"".concat(l,"/").concat(c," workspaces"):null].filter(Boolean).join(" \xb7 ")}function Ka(e,t){if(!e)return"Export";if("organization"===e.scope)return"Organization export";return t.get(e.workspaceId)||e.workspaceName||"Workspace"}function Qa(e){let t=e.isOpen,n=e.onClose,r=e.organizationId,o=e.organizationName,s=void 0===o?"":o,l=e.isOrgAdmin,d=void 0!==l&&l,u=e.exportableWorkspaces,m=void 0===u?[]:u;const p=(0,i.useState)("workspaces"),g=(0,a.A)(p,2),h=g[0],f=g[1],y=(0,i.useState)(()=>new Set),v=(0,a.A)(y,2),x=v[0],b=v[1],w=(0,i.useState)([]),k=(0,a.A)(w,2),A=k[0],N=k[1],C=(0,i.useState)(!0),S=(0,a.A)(C,2),E=S[0],I=S[1],D=(0,i.useState)(!1),P=(0,a.A)(D,2),T=P[0],R=P[1],O=(0,i.useMemo)(()=>{const e=new Map;
1for(const t of m)e.set(t.id,t.name||"Untitled workspace");return e},[m]),F=Boolean(r)&&(d||m.length>0);(0,i.useEffect)(()=>{t&&(f(d?"organization":"workspaces"),b(new Set(1===m.length?[m[0].id]:[])))},[t,d,m]);const L=(0,i.useCallback)(async()=>{if(!r||!F)return I(!1),void N([]);I(!0);try{const e=(0,ge.httpsCallable)((0,ge.getFunctions)(),"listExportJobs");let t=[];if(d){const n=(await e({organizationId:r})).data;t=(null===n||void 0===n?void 0:n.jobs)||[]}else{const n=await Promise.all(m.map(async t=>{try{const n=(await e({organizationId:r,workspaceId:t.id})).data;return(null===n||void 0===n?void 0:n.jobs)||[]}catch(n){return[]}})),o=new Map;for(const e of n)for(const t of e)null!==t&&void 0!==t&&t.jobId&&o.set(t.jobId,t);t=Array.from(o.values())}t.sort((e,t)=>{const n=e.createdAt?new Date(e.createdAt).getTime():0;return(t.createdAt?new Date(t.createdAt).getTime():0)-n}),N(t.slice(0,12))}catch(e){console.error("Failed to list export jobs:",e)}finally{I(!1)}},[r,F,d,m]);(0,i.useEffect)(()=>{t&&L()},[t,L]);const _=(0,i.useMemo)(()=>A.filter(e=>Ha.has(e.status)),[A]);(0,i.useEffect)(()=>{if(!t||0===_.length)return;const e=(0,ge.httpsCallable)((0,ge.getFunctions)(),"getExportJob"),n=setInterval(async()=>{try{const t=await Promise.all(_.map(async t=>(await e({jobId:t.jobId})).data||t));N(e=>{const n=new Map(e.map(e=>[e.jobId,e]));for(const r of t){if(null===r||void 0===r||!r.jobId)continue;const e=n.get(r.jobId);n.set(r.jobId,r),e&&Ha.has(e.status)&&"ready"===r.status?Ie.Ay.success("".concat(Ka(r,O)," ready to download")):e&&Ha.has(e.status)&&"failed"===r.status&&Ie.Ay.error(r.error||"Export failed")}return Array.from(n.values()).sort((e,t)=>{const n=e.createdAt?new Date(e.createdAt).getTime():0;return(t.createdAt?new Date(t.createdAt).getTime():0)-n})})}catch(t){console.error("Export job poll failed:",t)}},4e3);return()=>clearInterval(n)},[t,_,O]);if(!t)return null;const U=T||"workspaces"===h&&0===x.size||"organization"===h&&!d;return(0,We.jsx)("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center bg-black bg-opacity-50 p-4",children:(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-xl w-full max-w-lg max-h-[85vh] flex flex-col",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between p-4 border-b border-gray-200",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(0,We.jsx)(Ma.A,{className:"h-5 w-5 text-red-600"}),(0,We.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Export data"})]}),(0,We.jsx)("button",{type:"button",onClick:n,className:"text-gray-400 hover:text-gray-600","aria-label":"Close",children:(0,We.jsx)(c.A,{className:"h-6 w-6"})})]}),(0,We.jsx)("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:F?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("p",{className:"text-sm text-gray-600",children:"Download a zip of Word (.docx) documents (headings, formatting, images), plus JSON and files. We\u2019ll email a download link when ready (expires in 7 days)."}),d&&(0,We.jsxs)("div",{className:"space-y-2",children:[(0,We.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-gray-500",children:"What to export"}),(0,We.jsxs)("label",{className:"flex items-start gap-3 rounded-md border border-gray-200 px-3 py-2.5 cursor-pointer hover:bg-gray-50",children:[(0,We.jsx)("input",{type:"radio",name:"export-mode",className:"mt-1",checked:"organization"===h,onChange:()=>f("organization")}),(0,We.jsxs)("span",{children:[(0,We.jsx)("span",{className:"block text-sm font-medium text-gray-900",children:"Entire organization"}),(0,We.jsxs)("span",{className:"block text-xs text-gray-500 mt-0.5",children:["All workspaces in ",s||"this organization"]})]})]}),(0,We.jsxs)("label",{className:"flex items-start gap-3 rounded-md border border-gray-200 px-3 py-2.5 cursor-pointer hover:bg-gray-50",children:[(0,We.jsx)("input",{type:"radio",name:"export-mode",className:"mt-1",checked:"workspaces"===h,onChange:()=>f("workspaces")}),(0,We.jsxs)("span",{children:[(0,We.jsx)("span",{className:"block text-sm font-medium text-gray-900",children:"Selected workspaces"}),(0,We.jsx)("span",{className:"block text-xs text-gray-500 mt-0.5",children:"Choose one or more workspaces (one zip each)"})]})]})]}),"workspaces"===h&&(0,We.jsxs)("div",{className:"space-y-2",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-gray-500",children:"Worksp
1aces"}),m.length>1&&(0,We.jsx)("button",{type:"button",onClick:()=>{b(new Set(m.map(e=>e.id)))},className:"text-xs font-medium text-blue-600 hover:text-blue-700",children:"Select all"})]}),(0,We.jsx)("div",{className:"max-h-48 overflow-y-auto rounded-md border border-gray-200 divide-y divide-gray-100",children:0===m.length?(0,We.jsx)("p",{className:"px-3 py-3 text-sm text-gray-500",children:"No workspaces available to export."}):m.map(e=>(0,We.jsxs)("label",{className:"flex items-center gap-3 px-3 py-2.5 cursor-pointer hover:bg-gray-50",children:[(0,We.jsx)("input",{type:"checkbox",checked:x.has(e.id),onChange:()=>{return t=e.id,void b(e=>{const n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n});var t}}),(0,We.jsx)("span",{className:"text-sm text-gray-900 truncate",children:e.name||"Untitled workspace"})]},e.id))})]}),(0,We.jsx)("div",{className:"pt-1",children:(0,We.jsx)(St.A,{type:"button",onClick:async()=>{if(!r)return;if("organization"===h){if(!window.confirm("Export ".concat(s||"this organization","?\n\nWe\u2019ll prepare a zip of Word (.docx) documents, JSON, and files for every workspace. This may take a few minutes. You\u2019ll get a download link here and by email (kept for 7 days).")))return;try{R(!0);const e=(0,ge.httpsCallable)((0,ge.getFunctions)(),"requestOrganizationExport"),t=(await e({organizationId:r})).data;null!==t&&void 0!==t&&t.job?N(e=>[t.job,...e.filter(e=>e.jobId!==t.job.jobId)]):await L(),Ie.Ay.success("Export started. We\u2019ll email you when it\u2019s ready.")}catch(o){console.error("Export request failed:",o);const e=(null===o||void 0===o?void 0:o.message)||"Failed to start export";String(e).includes("already in progress")||"functions/already-exists"===(null===o||void 0===o?void 0:o.code)?(Ie.Ay.error("An export is already in progress. Please wait for it to finish."),L()):Ie.Ay.error(e.replace(/^Firebase:\s*/i,"").replace(/\s*\(.*\)\s*$/,"")||"Failed to start export")}finally{R(!1)}return}const e=Array.from(x);if(0===e.length)return void Ie.Ay.error("Select at least one workspace to export");const t=e.map(e=>O.get(e)||"workspace"),n=1===e.length?t[0]:"".concat(e.length," workspaces (").concat(t.slice(0,3).join(", ")).concat(t.length>3?"\u2026":"",")");if(window.confirm("Export ".concat(n,"?\n\nWe\u2019ll prepare a zip of Word (.docx) documents, JSON, and files for each selection. This may take a few minutes. You\u2019ll get a download link here and by email (kept for 7 days).")))try{R(!0);const t=(0,ge.httpsCallable)((0,ge.getFunctions)(),"requestWorkspaceExport"),n=[];for(const r of e)try{const e=(await t({workspaceId:r})).data;null!==e&&void 0!==e&&e.job&&n.push(e.job)}catch(o){const e=(null===o||void 0===o?void 0:o.message)||"Failed to start export";String(e).includes("already in progress")||"functions/already-exists"===(null===o||void 0===o?void 0:o.code)?Ie.Ay.error("Export already in progress for ".concat(O.get(r)||"workspace")):Ie.Ay.error("".concat(O.get(r)||"Workspace",": ")+(e.replace(/^Firebase:\s*/i,"").replace(/\s*\(.*\)\s*$/,"")||"Failed to start export"))}n.length>0&&(N(e=>{const t=new Map(e.map(e=>[e.jobId,e]));for(const r of n)t.set(r.jobId,r);return Array.from(t.values())}),Ie.Ay.success(1===n.length?"Export started. We\u2019ll email you when it\u2019s ready.":"".concat(n.length," exports started. We\u2019ll email you when they\u2019re ready."))),await L()}finally{R(!1)}},loading:T,disabled:U,leadingIcon:(0,We.jsx)(kn.A,{className:"h-4 w-4"}),className:"w-full justify-center",children:T?"Starting\u2026":"Start export"})}),(0,We.jsxs)("div",{className:"border-t border-gray-100 pt-4 space-y-3",children:[(0,We.jsx)("p",{className:"text-xs font-medium uppercase tracking-wide text-gray-500",children:"Recent exports"}),E?(0,We.jsxs)("div",{className:"flex items-center gap-2 text-sm text-gray-500",children:[(0,We.jsx)(Se.y$,{size:"sm",className:"text-gray-500"}),"Checking recent exports\u2026"]}):0===A.length?(0,We.jsx)("p",{className:"text-sm text-gray-500",children:"No exports yet."}):A.map(e=>(0,We.jsxs)("div",{className:"rounded-md border border-gray-200 px-3 py-2.5 text-sm",children:[(0,We.jsx)("div",{className:"flex items-start justify-between gap-2",children:(0,We.jsxs)("div",{className:"min-w-0",children:[(0,We.jsx)("p",{className:"font-medium text-gray-900 truncate",children:Ka(e,O)}),(0,We.jsxs)("p",{className:"text-xs text-gray-500 mt-0.5 capitalize",children:[e.status,e.createdAt?" \xb7 ".concat(new Date(e.createdAt).toLocaleStr
1ing()):""]})]})}),Ha.has(e.status)&&(0,We.jsxs)("div",{className:"mt-2 flex items-start gap-2 text-blue-800",children:[(0,We.jsx)(Se.y$,{size:"sm",className:"mt-0.5 text-blue-600"}),(0,We.jsx)("p",{className:"text-xs",children:Ga(e)||"Preparing your download\u2026"})]}),"ready"===e.status&&(0,We.jsx)("div",{className:"mt-2 rounded-md border border-green-100 bg-green-50 px-2.5 py-2 text-green-800",children:(0,We.jsxs)("div",{className:"flex items-start gap-2",children:[(0,We.jsx)(Ja.A,{className:"h-4 w-4 mt-0.5 flex-shrink-0"}),(0,We.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,We.jsx)("p",{className:"text-xs font-medium",children:"Ready to download"}),(0,We.jsxs)("p",{className:"text-xs mt-0.5",children:[e.documentCount||0," document",1===(e.documentCount||0)?"":"s",e.expiresAt?" \xb7 expires ".concat(new Date(e.expiresAt).toLocaleString()):""]}),(0,We.jsxs)("div",{className:"mt-2 flex flex-wrap gap-2",children:[(0,We.jsx)(St.A,{type:"button",size:"sm",onClick:()=>(e=>{null!==e&&void 0!==e&&e.downloadUrl&&window.open(e.downloadUrl,"_blank","noopener,noreferrer")})(e),disabled:!e.downloadUrl,leadingIcon:(0,We.jsx)(kn.A,{className:"h-4 w-4"}),children:"Download zip"}),(0,We.jsxs)("button",{type:"button",onClick:()=>(async e=>{if(null!==e&&void 0!==e&&e.jobId)try{const t=(0,ge.httpsCallable)((0,ge.getFunctions)(),"getExportJob"),n=(await t({jobId:e.jobId})).data;n&&(N(e=>e.map(e=>e.jobId===n.jobId?n:e)),n.downloadUrl&&Ie.Ay.success("Download link refreshed"))}catch(t){console.error("Refresh export link failed:",t),Ie.Ay.error("Could not refresh download link")}})(e),className:"inline-flex items-center gap-1.5 rounded-md border border-green-200 bg-white px-3 py-1.5 text-xs font-medium text-green-800 hover:bg-green-50",children:[(0,We.jsx)(j.A,{className:"h-3.5 w-3.5"}),"Refresh link"]})]})]})]})}),"failed"===e.status&&(0,We.jsxs)("div",{className:"mt-2 flex items-start gap-2 text-red-800",children:[(0,We.jsx)(qa.A,{className:"h-4 w-4 mt-0.5 flex-shrink-0"}),(0,We.jsx)("p",{className:"text-xs",children:e.error||"Something went wrong."})]}),"expired"===e.status&&(0,We.jsx)("p",{className:"mt-2 text-xs text-gray-500",children:"This export expired. Start a new one to download again."})]},e.jobId))]})]}):(0,We.jsx)("p",{className:"text-sm text-gray-600",children:"Only organization or workspace admins can export data."})})]})})}var Ya=n(12602),Za=n(82665),$a=n(80813);const Xa=["folderId"],ei=["folderId"],ti=["_editorJsonForPreservation","_editorHtmlForPreservation","aiGeneratedToolbarUntil","lastAIGenerateOptions","showAIRevisionBar","_pdfCanonicalCopy","_pdfIndexPlaintext"],ni=(0,i.lazy)(()=>Promise.all([n.e(8706),n.e(5607),n.e(9219),n.e(1062),n.e(74)]).then(n.bind(n,86150))),ri=(0,i.lazy)(()=>Promise.all([n.e(8041),n.e(8968),n.e(2212),n.e(7015)]).then(n.bind(n,57015))),oi=(0,i.lazy)(()=>Promise.all([n.e(8706),n.e(1062)]).then(n.bind(n,1062))),ai=(0,i.lazy)(()=>n.e(448).then(n.bind(n,60448))),ii=(0,i.lazy)(()=>Promise.all([n.e(8279),n.e(8041),n.e(1422),n.e(8968),n.e(3319)]).then(n.bind(n,93857))),si=(0,i.lazy)(()=>n.e(9005).then(n.bind(n,9005))),li=(0,i.lazy)(()=>Promise.all([n.e(1567),n.e(9411)]).then(n.bind(n,59411))),di=(0,i.lazy)(()=>n.e(4236).then(n.bind(n,84236))),ci=(0,i.lazy)(()=>n.e(150).then(n.bind(n,60150))),ui=(0,i.lazy)(()=>Promise.all([n.e(1332),n.e(2703)]).then(n.bind(n,62703))),mi=(0,We.jsx)("div",{className:"flex items-center justify-center py-16",children:(0,We.jsx)(Se.y$,{size:"lg",className:"text-blue-600"})});function pi(e){const t=e&&e.pdfSources;Array.isArray(t)&&t.length>0&&Ie.Ay.custom(e=>(0,We.jsxs)("div",{className:"max-w-sm rounded-brand-md border border-hairline bg-surface p-4 shadow-lg text-left",children:[(0,We.jsx)("p",{className:"text-sm font-medium text-on-surface mb-2",children:"Sources used for this draft"}),(0,We.jsx)(ft.E,{pdfSources:t}),(0,We.jsx)("button",{type:"button",className:"mt-3 text-xs text-gray-600 hover:text-gray-800",onClick:()=>Ie.Ay.dismiss(e.id),children:"Dismiss"})]}),{duration:14e3,id:"stream-ai-pdf-sources"})}function gi(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=(0,Tr.K1)(e.userPrompt,e.documentType);return"yes"===n||"no"!==n&&!0===t.signatureBlocksInDraftUnsure}function hi(e,t){const n="string"===typeof t?t.trim():"";if(!n)return"string"===typeof e?e:"";const r="string"===typeof e?e.trim():"";return r?"".concat(r,"\n\n---\nReference material from uploaded PDF(s):\n").concat(n,"\n---"):"Reference material from uploaded PDF(s):\n".concat(n)}function fi(e){null!==e&&void 0!==e&&e.parentNode&&e.parentNode.removeChild(e)}function yi(e,t){let n=t.docId,r=t.setDraggedDocId,o=t.ghostRef;if((a=e.target)instanceof Element&&Boolean(a.closest('button, a, input, textarea, select, label, [data-action], [data-no-drag], [role="dialog"]')))return e.preventDefault(),!1;var a;
1e.stopPropagation(),fi(o.current),o.current=null,r(n),e.dataTransfer.setData("docId",n),e.dataTransfer.effectAllowed="move";const i=e.currentTarget.closest("[data-doc-card]")||e.currentTarget;return i&&(o.current=function(e,t,n,r){if(!e||!t)return null;const o=e.getBoundingClientRect(),a=e.cloneNode(!0);a.setAttribute("data-doc-card-drag-ghost","true"),a.querySelectorAll("img").forEach(e=>{e.setAttribute("draggable","false"),e.style.webkitUserDrag="none"}),Object.assign(a.style,{position:"fixed",top:"-9999px",left:"-9999px",width:"".concat(o.width,"px"),height:"".concat(o.height,"px"),margin:"0",opacity:"0.95",boxShadow:"0 12px 28px rgba(15, 23, 42, 0.22)",border:"2px solid #3b82f6",borderRadius:"0.5rem",pointerEvents:"none",zIndex:"99999",background:"#fff",overflow:"hidden"}),document.body.appendChild(a);const i=Number.isFinite(n)?Math.max(0,Math.min(o.width,n-o.left)):Math.min(o.width/2,80),s=Number.isFinite(r)?Math.max(0,Math.min(o.height,r-o.top)):24;return t.setDragImage(a,i,s),a}(i,e.dataTransfer,e.clientX,e.clientY),i.style.opacity="0.35"),!0}function vi(e,t){let n=t.setDraggedDocId,r=t.setDragOverIndex,o=t.ghostRef;fi(o.current),o.current=null;const a=e.currentTarget.closest("[data-doc-card]")||e.currentTarget;a&&(a.style.opacity="1",a.style.transform=""),setTimeout(()=>{n(null),r(null)},100)}async function xi(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!e)return;const r=(0,ge.httpsCallable)((0,ge.getFunctions)(),"indexWorkspaceForChat",{timeout:3e5});let o;if(Array.isArray(t)&&t.length>0){const n=t.filter(e=>!e.decryptionFailed&&!e.processingError),a=Array.from(new Map(n.map(e=>[e.id,e])).values()).map(e=>{let t="";return t=e.textContent&&e.textContent.trim()?e.textContent:e.content&&e.content.trim()?e.content:e.extractedContent&&e.extractedContent.trim()?e.extractedContent:e.text&&e.text.trim()?e.text:e.editorHtml&&e.editorHtml.trim()?e.editorHtml:"Document: ".concat((0,_e.Od)(e,"Untitled")," (no content available)"),{id:e.id,title:(0,_e.Od)(e,"Untitled"),content:t,type:e.type||"document",isEncrypted:e.isEncrypted||!1,wasDecrypted:e.isEncrypted&&!e.decryptionFailed,fileType:e.fileType||"",fileName:e.fileName||"",viewerMode:e.viewerMode||""}});o=await r({workspaceId:e,documents:a})}else o=await r({workspaceId:e});const a=o&&"object"===typeof o&&"data"in o?o.data:o;n.fromEncryptedPostSave&&a&&0===Number(a.totalChunks)&&console.error("Post-save RAG: index returned 0 chunks (server Firestore reindex for encrypted save). If public/shared search still misses the document, re-save or reindex the workspace; check function logs for decrypt errors.",{workspaceId:e})}function bi(e,t,n){const r=Array.isArray(e)?e:[],o=null===t||void 0===t?void 0:t.id;if(!o)return r;const a=null!=n?String(n):"";return[...r.filter(e=>e&&e.id&&String(e.id)!==String(o)&&(!a||String(e.id)!==a)),t]}const wi=e=>{let t=e.documentId,n=e.workspaceIds,r=e.workspaceList;const o=jn(t,n),a=o.isLive,i=o.liveSource,s=o.liveWorkspaceId;if(!a)return null;let d;if("document"===i)d="This document has its own public link. It was shared individually, not through the workspace.";else if("workspace"===i&&null!==r&&void 0!==r&&r.length&&s){var c,u;const e=null!==(c=null===(u=r.find(e=>e.id===s))||void 0===u?void 0:u.name)&&void 0!==c?c:s;d="Shared publicly via ".concat(e)}else d="workspace"===i?"Shared publicly via this workspace.":void 0;return(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700",title:d,children:[(0,We.jsx)(l.A,{className:"w-3 h-3"}),"Live"]})};function ki(e){let t=e.docId,n=e.fileName,r=e.title,o=e.onRename;const s="string"===typeof n&&n.trim()||"string"===typeof r&&r.trim()||"PDF",l=(0,i.useState)(!1),d=(0,a.A)(l,2),c=d[0],u=d[1],m=(0,i.useState)(s),p=(0,a.A)(m,2),g=p[0],h=p[1],f=(0,i.useRef)(null);(0,i.useEffect)(()=>{c||h(s)},[s,c]),(0,i.useEffect)(()=>{c&&f.current&&(f.current.focus(),f.current.select())},[c]);const y=(0,i.useCallback)(()=>{const e=g.trim();u(!1),t&&e&&e!==s&&o(e,t)},[g,s,t,o]),v=e=>{"Enter"===e.key?(e.preventDefault(),y()):"Escape"===e.key&&(e.preventDefault(),h(s),u(!1))};return t?c?(0,We.jsx)("input",{ref:f,type:"text",value:g,onChange:e=>h(e.target.value),onBlur:y,onKeyDown:v,"aria-label":"PDF file name",className:"w-full min-w-0 text-xl sm:text-2xl font-bold text-gray-900 px-2 py-1 rounded-lg border border-blue-300 focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white"}):(0,We.jsx)("h1",{className:"text-xl sm:text-2xl font-bold text-gray-900 truncate min-w-0 m-0",children:(0,We.jsx)("button",{type:"button",onClick:()=>u(!0),className:"w-full min-w-0 text-left truncate rounded px-1 -mx-1 py-0.5 hover:bg-gray-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 cursor-text",title:"Edit file name",children:s})}):(0,We.jsx)("h1",{className:"text-xl sm:text-2xl font-bold text-gray-900 truncate",children:s})}const Ai=()=>{var e,t;const K=(0,mo.A)(),Z=K.currentUser,X=K.user,te=K.setUser,le=K.userProfile,de=(K.setUserProfile,K.loading),ce=K.setLoading,ue=K.organizationId,fe=K.setOrganizationId,ye=K.currentOrganizationId,ve=K.setCurrentOrganizationId,xe=K.currentUserRole,be=K.userPlan,we=K.hasUnseenUpdates,
1ke=K.setHasUnseenUpdates,Ae=K.appUpdatesVersion,je=K.appUpdatesIsBeta,Ne=K.orgResolved,Ce=(0,$a.V)(),Ee=Ce.setActiveWorkspace,De=Ce.setWorkspaceList,Te=Ce.setIsAgentSidebarOpen,Re=Ce.setActiveDocumentId,Oe=Ce.registerKbActionHandler,Fe=(0,z.Zp)(),Le=(0,z.zy)();(0,i.useEffect)(()=>{if(null===X||void 0===X||!X.uid)return;if(sessionStorage.getItem("visitRecorded"))return;(0,ge.httpsCallable)((0,ge.getFunctions)(),"recordVisit")().then(()=>sessionStorage.setItem("visitRecorded","1")).catch(()=>{})},[null===X||void 0===X?void 0:X.uid]),(0,i.useEffect)(()=>{if(null===X||void 0===X||!X.uid||X.isAnonymous||!Ne||"admin"!==xe)return;if(Ki.current)return;Ki.current=!0;const e="onboarding-completed-".concat(X.uid);"true"!==localStorage.getItem(e)&&(async()=>{try{const o=(0,B.doc)(G.db,"users",X.uid),a=await(0,B.getDoc)(o);if(a.exists()&&a.data().integrationsOnboardingCompletedAt)return void localStorage.setItem(e,"true");try{const e=(0,Pe.getSelectedOrganizationId)()||ue;if(e){const r=await(0,Pe.getUserOrganizationData)(e);var t,n;if(r)Vi(r.name||""),Gi((null===(t=r.settings)||void 0===t||null===(n=t.branding)||void 0===n?void 0:n.logoUrl)||null)}}catch(r){}Mi(!0)}catch(o){(0,W.gg)("Onboarding check failed, skipping:",o)}})()},[null===X||void 0===X?void 0:X.uid,null===X||void 0===X?void 0:X.isAnonymous,Ne,xe,ue]),(0,i.useEffect)(()=>{const e=()=>{Ki.current=!1};return window.addEventListener("rerunOnboarding",e),()=>window.removeEventListener("rerunOnboarding",e)},[]);const Ue=(0,i.useCallback)(async e=>{if(Mi(!1),null===X||void 0===X||!X.uid)return;try{const t=(0,B.doc)(G.db,"users",X.uid),n=await(0,B.getDoc)(t),r={integrationsOnboardingCompletedAt:(0,B.O5)(),integrationsOnboardingWorkType:(null===e||void 0===e?void 0:e.workType)||null};n.exists()?await(0,B.mZ)(t,r):await(0,B.BN)(t,r,{merge:!0}),localStorage.setItem("onboarding-completed-".concat(X.uid),"true")}catch(n){console.error("Failed to persist onboarding completion:",n),localStorage.setItem("onboarding-completed-".concat(X.uid),"true")}const t=ue||(0,Pe.getSelectedOrganizationId)();if(t&&null!==e&&void 0!==e&&e.workType)try{const n=(0,Rr.GY)(e.workType,e.answers||{});await(0,B.mZ)((0,B.doc)(G.db,"organizations",t),{"settings.categoryPresets":n,updatedAt:(0,B.O5)()})}catch(r){console.warn("Could not apply onboarding category presets:",r)}null!==e&&void 0!==e&&e.wantsStripe&&(0,Ie.Ay)("Head to Settings \u2192 Integrations to connect Stripe.",{icon:"\ud83d\udcb3",duration:6e3}),null!==e&&void 0!==e&&e.wantsChatbot&&(0,Ie.Ay)("Share a workspace to set up your AI chatbot widget.",{icon:"\ud83e\udd16",duration:6e3})},[null===X||void 0===X?void 0:X.uid,ue]),Me=(0,i.useCallback)(async()=>{if(Mi(!1),null!==X&&void 0!==X&&X.uid)try{const e=(0,B.doc)(G.db,"users",X.uid),t=await(0,B.getDoc)(e),n={integrationsOnboardingCompletedAt:(0,B.O5)()};t.exists()?await(0,B.mZ)(e,n):await(0,B.BN)(e,n,{merge:!0}),localStorage.setItem("onboarding-completed-".concat(X.uid),"true")}catch(e){console.error("Failed to persist onboarding skip:",e),localStorage.setItem("onboarding-completed-".concat(X.uid),"true")}},[null===X||void 0===X?void 0:X.uid]),ze=(0,i.useState)(null),Be=(0,a.A)(ze,2),Ve=Be[0],Je=Be[1],qe=(0,i.useRef)(null);(0,i.useLayoutEffect)(()=>{qe.current=Ve},[Ve]);const He=(0,i.useState)(!0),Ge=(0,a.A)(He,2),Ke=Ge[0],Qe=Ge[1],$e=(0,i.useState)(!1),Xe=(0,a.A)($e,2),et=Xe[0],tt=Xe[1],nt=(0,i.useState)(!1),rt=(0,a.A)(nt,2),ot=rt[0],at=rt[1],it=(0,i.useCallback)(()=>{ke(!1)},[]),st=(0,i.useState)(""),lt=(0,a.A)(st,2),dt=lt[0],ct=lt[1],ut=(0,i.useState)([]),mt=(0,a.A)(ut,2),pt=mt[0],gt=mt[1],ht=(0,i.useState)(!1),ft=(0,a.A)(ht,2),yt=ft[0],vt=ft[1],xt=(0,i.useState)(!1),bt=(0,a.A)(xt,2),wt=bt[0],kt=bt[1],At=(0,i.useRef)(0),jt=(0,i.useRef)(!1),Nt=(0,i.useRef)(null),Et=(0,i.useState)(""),Dt=(0,a.A)(Et,2),Pt=Dt[0],Tt=Dt[1],Rt=(0,i.useRef)(null),Mt=(0,i.useRef)(null),qt=(0,i.useCallback)(()=>{At.current+=1,ct(""),gt([]),kt(!1),vt(!1)},[]),Ht=(0,i.useState)({}),Gt=(0,a.A)(Ht,2),Kt=Gt[0],Qt=Gt[1],Zt=(0,i.useState)(null),$t=(0,a.A)(Zt,2),Xt=$t[0],nn=$t[1],rn=(0,i.useState)(!1),on=(0,a.A)(rn,2),an=on[0],sn=(on[1],(0,i.use
1State)(()=>{try{const e=localStorage.getItem("kbViewMode");if("card"===e||"continuous"===e||"brainMap"===e)return e}catch(e){}return"card"})),ln=(0,a.A)(sn,2),dn=ln[0],cn=ln[1],un=(0,i.useState)(()=>{const e=localStorage.getItem("documentLayout");return"list"===e||"grid"===e?e:"grid"}),mn=(0,a.A)(un,2),pn=mn[0],gn=mn[1],hn=(0,i.useState)(!1),fn=(0,a.A)(hn,2),yn=fn[0],vn=fn[1],xn=(0,i.useState)(window.innerWidth<1024),kn=(0,a.A)(xn,2),An=kn[0],jn=kn[1],Cn=(0,i.useState)({documents:[],structure:{},processed:!1,totalDocumentCount:0}),In=(0,a.A)(Cn,2),Pn=In[0],Rn=In[1];(0,i.useEffect)(()=>{if(!Z||null!==X&&void 0!==X&&X.isAnonymous)return;const e=new URLSearchParams(Le.search).get("doc");if(!e||!String(e).trim())return void(Rt.current=null);const t=String(e).trim();if(qe.current===t)return void(Rt.current=t);const n=null===Pn||void 0===Pn?void 0:Pn.documents;if(!Array.isArray(n)||0===n.length)return;n.some(e=>e&&String(e.id)===t)&&Rt.current!==t&&(Rt.current=t,ir(null),Je(t),"undefined"!==typeof window&&window.innerWidth<1024&&Qe(!1))},[Z,null===X||void 0===X?void 0:X.isAnonymous,null===Pn||void 0===Pn?void 0:Pn.documents,Le.search]),(0,i.useEffect)(()=>{if(!Z||null!==X&&void 0!==X&&X.isAnonymous)return;const e=(0,Zr.oS)(Ve)?String(Ve).trim():null,t=new URLSearchParams(Le.search.startsWith("?")?Le.search.slice(1):Le.search||"").get("doc"),n=null!=t&&String(t).trim()?String(t).trim():null;if(e){if(e===n)return void(Mt.current=e)}else{if(!n)return void(Mt.current=null);if(null==Mt.current)return}const r=(0,Zr.RP)(Le.search,e),o=r.search;r.changed?(Mt.current=e,Fe({pathname:Le.pathname||"/",search:o?"?".concat(o):""},{replace:!0})):Mt.current=e},[Ve,Z,null===X||void 0===X?void 0:X.isAnonymous,Le.search,Le.pathname,Fe]);const On=(0,i.useRef)(null),Fn=(0,i.useState)(null),Ln=(0,a.A)(Fn,2),_n=Ln[0],Un=Ln[1],Mn=(0,i.useState)(""),zn=(0,a.A)(Mn,2),qn=zn[0],Kn=(zn[1],(0,i.useState)(null)),Yn=(0,a.A)(Kn,2),Zn=Yn[0],$n=Yn[1],Xn=(0,i.useState)(!1),er=(0,a.A)(Xn,2),tr=er[0],nr=er[1],rr=(0,i.useState)(null),or=(0,a.A)(rr,2),ar=or[0],ir=or[1],sr=(0,i.useRef)(null),lr=(0,i.useRef)(null);(0,i.useEffect)(()=>{sr.current=ar},[ar]);const dr=(0,i.useState)(!1),cr=(0,a.A)(dr,2),ur=cr[0],mr=cr[1],pr=(0,i.useState)(new Set),gr=(0,a.A)(pr,2),hr=gr[0],fr=gr[1],yr=(0,i.useMemo)(()=>!Ve||String(Ve).startsWith("new_")?null:Ve,[Ve]);(0,i.useEffect)(()=>(Re(yr),()=>Re(null)),[yr,Re]);const vr=(0,i.useState)(()=>{try{return"true"===localStorage.getItem("showMobileDebug")}catch(e){return!1}}),xr=(0,a.A)(vr,2),wr=xr[0],kr=xr[1],Ar=(0,i.useState)("documents"),jr=(0,a.A)(Ar,2),Nr=jr[0],Cr=jr[1],Sr=(0,i.useState)([]),Er=(0,a.A)(Sr,2),Or=Er[0],Fr=Er[1],_r=(0,i.useState)({completed:!1,userId:null,orgId:null,error:null}),Ur=(0,a.A)(_r,2),Br=Ur[0],Wr=Ur[1],Vr=(0,i.useState)(()=>"undefined"===typeof window?null:(0,$r.HV)()),qr=(0,a.A)(Vr,2),Hr=qr[0],Gr=qr[1],Qr=(0,i.useState)(!1),Xr=(0,a.A)(Qr,2),eo=Xr[0],po=Xr[1],go=(0,i.useState)(""),ho=(0,a.A)(go,2),xo=ho[0],bo=ho[1],wo=(0,i.useRef)(Or);wo.current=Or;const ko=(0,i.useRef)(Br);ko.current=Br;const Ao=(0,i.useRef)(new Set),jo=(0,i.useMemo)(()=>null!==Or&&void 0!==Or&&Or.length?Or.map(e=>String(e.id)).sort().join(","):"",[Or]),No=(0,i.useMemo)(()=>{const e=ye||ue,t=Array.isArray(Or)?Or:[],n=e?t.filter(t=>!t.organizationId||t.organizationId===e):t;return"admin"===xe?n.map(e=>({id:e.id,name:e.name||"Untitled workspace"})):n.filter(e=>"admin"===e.userRole).map(e=>({id:e.id,name:e.name||"Untitled workspace"}))},[Or,xe,ye,ue]),Co="admin"===xe||No.length>0,Io=(0,i.useState)(()=>{if("undefined"!==typeof window){return localStorage.getItem(en.ut)||null}return null}),Fo=(0,a.A)(Io,2),Lo=Fo[0],_o=Fo[1],Uo=(0,i.useState)(()=>{if("undefined"!==typeof window){return localStorage.getItem("activeView")||"global"}return"global"}),Mo=(0,a.A)(Uo,2),zo=Mo[0],Bo=Mo[1],Wo=(0,i.useMemo)(()=>null!==X&&void 0!==X&&X.uid&&(ye||ue||(0,Pe.getSelectedOrganizationId)())||null,[ye,ue,null===X||void 0===X?void 0:X.uid]),Vo=(0,i.useCallback)((e,t)=>{t?(0,W.gg)("[OrgSwitch] Workspace fetch completed with error:",{orgId:e,error:t}):(0,W.gg)("[OrgSwitch] Workspace fetch completed:",{orgId:e}),Wr({completed:!0,userId:(null===X||void 0===X?void 0:X.uid)||null,orgId:e||null,error:t?{code:(null===t||void 0===t?void 0:t.code)||null,message:(null===t||void 0===t?void 0:t.message)||String(t)}:null})},[null===X||void 0===X?void 0:X.uid]);(0,i.useEffect)(()=>{const e=(null===X||void 0===X?void 0:X.uid)||null,t=Wo||null;Wr(n=>n.userId===e&&n.orgId===t?n:{completed:!1,userId:e,orgId:t,error:null})},[Wo,null===X||void 0===X?void 0:X.uid]),(0,i.useEffect)(()=>
1{if(null===X||void 0===X||!X.uid||X.isAnonymous||!Ne||!Br.completed)return;if(!Array.isArray(Or)||0===Or.length)return;const e=ye||ue||(0,Pe.getSelectedOrganizationId)();if(!e)return;const t=Or.find(e=>!0===(null===e||void 0===e?void 0:e.isDefault))||Or.find(e=>"Default Workspace"===(null===e||void 0===e?void 0:e.name));if(null===t||void 0===t||!t.id)return;const n="".concat(X.uid,":").concat(e,":").concat(t.id);if(Ao.current.has(n))return;if((Pn.documents||[]).some(e=>{const n=Array.isArray(e.workspaceIds)?e.workspaceIds.map(String):[];return e.title===Za.oN&&(String(e.workspaceId||"")===String(t.id)||n.includes(String(t.id)))}))return void Ao.current.add(n);let r=!1;return Ao.current.add(n),(async()=>{try{const n=await(0,Pe.getUserOrganizationData)(e);if(!("client"===(null===n||void 0===n?void 0:n.type)&&Boolean((null===n||void 0===n?void 0:n.parentOrganizationId)||(null===n||void 0===n?void 0:n.createdByPartnerUserId)))||r)return;const a=(0,B.P)((0,B.rJ)(G.db,"knowledgeBaseDocuments"),(0,B._M)("workspaceIds","array-contains",t.id)),i=await(0,B.GG)(a);if(i.docs.some(e=>{const t=e.data();return(null===t||void 0===t?void 0:t.title)===Za.oN})||r)return;const s=(0,Za.Uo)({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_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #69 from grigerny/cursor/native-document-tables-6648\n\nNative document tables for editor and MCP agents",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_6MQChUZTeZEjuh9PAEPmwanHsu8y",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"fe8e0cad17d5c751081fbff8964f57a16f15178c",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-o7e1bdtta-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_HELP_CENTER_URL),l=await(0,Y.cI)(JSON.stringify(s),X.uid,[t.id]),d=(0,Za.Hp)(),c={title:Za.oN,category:"Welcome",tags:["welcome","getting-started","tutorial"],workspace:t.name||"Default Workspace",workspaceIds:[t.id],workspaceId:t.id,organizationId:e,userId:X.uid,createdAt:(0,B.O5)(),updatedAt:(0,B.O5)(),createdBy:X.uid,isTemplate:!1,isPublic:!1,isEncrypted:!0,encryptionMethod:"dual",userEncryptedResult:l.userEncryptedResult,workspaceEncryptedResults:l.workspaceEncryptedResults,fileType:"document",type:"document",isDefault:!0,textContent:"[Encrypted Content]",coverImageUrl:(0,Za.OZ)(),summary:d.summary,keyElements:d.keyElements,relatedTopics:d.relatedTopics,status:"completed",fileSize:0},u=await(0,B.gS)((0,B.rJ)(G.db,"knowledgeBaseDocuments"),c);if(r)return;const m=new Date,p=(0,o.A)((0,o.A)({},c),{},{id:u.id,createdAt:m,updatedAt:m,uploadedAt:m});Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:Array.from(new Map([p,...e.documents||[]].map(e=>[e.id,e])).values()),processed:!0})),window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!1}})),(0,W.gg)("\u2705 Created partner client welcome document:",{organizationId:e,workspaceId:t.id,documentId:u.id})}catch(a){Ao.current.delete(n),r||console.error("\u26a0\ufe0f Failed to create partner client welcome document:",a)}})(),()=>{r=!0}},[ye,Pn.documents,ue,Ne,null===X||void 0===X?void 0:X.isAnonymous,null===X||void 0===X?void 0:X.uid,Br.completed,Or]),(0,i.useEffect)(()=>
1{if("undefined"===typeof window)return;const e=()=>{Gr((0,$r.HV)())};return e(),window.addEventListener("focus",e),window.addEventListener("visibilitychange",e),window.addEventListener("storage",e),window.addEventListener($r.E5,e),()=>{window.removeEventListener("focus",e),window.removeEventListener("visibilitychange",e),window.removeEventListener("storage",e),window.removeEventListener($r.E5,e)}},[]);const Jo=(0,i.useCallback)(async()=>{if(Hr&&G.j2.currentUser){po(!0),bo(""),console.info("[DomainJoin][App] retry requested from dashboard",{userId:G.j2.currentUser.uid,hasPendingDomainJoinSlug:Boolean(Hr),emailVerified:G.j2.currentUser.emailVerified});try{await(0,$r.LA)();const e=G.j2.currentUser;if(null===e||void 0===e||!e.emailVerified){try{await(0,he.gA)(e)}catch(n){"auth/too-many-requests"!==(null===n||void 0===n?void 0:n.code)&&console.warn("Could not send verification email for pending domain join:",n)}return void bo("Check your email for a sign-in or verification link from Based, then return here to finish joining your client workspace.")}const t=await(0,$r.VJ)({slug:Hr});if(null===t||void 0===t||!t.organizationId)throw new Error("The join request completed without an organization.");console.info("[DomainJoin][App] retry join succeeded",{userId:(null===e||void 0===e?void 0:e.uid)||null,organizationId:t.organizationId,defaultWorkspaceId:t.defaultWorkspaceId||null});const r=await(0,Pe.getUserOrganizationData)(t.organizationId,!0);r&&(fe(r.id),ve(r.id)),(0,$r.Uc)(),(0,$r.k4)(Hr),Gr(null),bo(""),window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!0}})),Ie.Ay.success("Your client workspace is ready.")}catch(r){var e,t;if(console.error("[DomainJoin] Manual retry failed:",r),console.info("[DomainJoin][App] retry join failed",{userId:(null===(e=G.j2.currentUser)||void 0===e?void 0:e.uid)||null,code:(null===r||void 0===r?void 0:r.code)||null,reason:(null===r||void 0===r||null===(t=r.details)||void 0===t?void 0:t.reason)||null,message:(null===r||void 0===r?void 0:r.message)||null}),(0,$r.fh)(r))return(0,$r.Uc)(),Gr(null),void Ie.Ay.error("This client invite is no longer available.");bo((null===r||void 0===r?void 0:r.message)||"Unable to finish joining this client workspace.")}finally{po(!1)}}},[Hr,ve,fe]),qo=Br.completed&&Br.userId===((null===X||void 0===X?void 0:X.uid)||null)&&Br.orgId===(Wo||null),Ho=qo?Br.error:null;(0,i.useEffect)(()=>{qo&&((null===Or||void 0===Or?void 0:Or.length)>0||Rn(e=>e.processed?e:(0,o.A)((0,o.A)({},e),{},{processed:!0})))},[qo,null===Or||void 0===Or?void 0:Or.length]),(0,i.useEffect)(()=>{console.info("[DomainJoin][App] pending join/workspace state",{hasPendingDomainJoinSlug:Boolean(Hr),userId:(null===X||void 0===X?void 0:X.uid)||null,currentOrganizationId:ye||null,organizationId:ue||null,selectedOrgId:(0,Pe.getSelectedOrganizationId)()||null,effectiveWorkspaceOrgId:Wo||null,activeView:zo,workspaceCount:(null===Or||void 0===Or?void 0:Or.length)||0,workspaceFetchState:Br,workspaceFetchCompleted:qo,workspaceFetchError:Ho,orgResolved:Ne})},[ye,Wo,zo,ue,Ne,Hr,null===X||void 0===X?void 0:X.uid,qo,Ho,Br,null===Or||void 0===Or?void 0:Or.length]),(0,i.useEffect)(()=>{dt.trim()&&(yt||wt)&&qt()},[Lo,zo]),(0,i.useEffect)(()=>{Nl(new Set)},[Lo,zo,dn]);const Go=(0,i.useCallback)(e=>{Nl(t=>{const n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),Ko=(0,i.useCallback)(e=>{e&&0!==e.length&&Nl(new Set(e.map(e=>e.id)))},[]),Qo=(0,i.useCallback)(()=>{Nl(new Set)},[]),Yo=(0,i.useState)(!1),Zo=(0,a.A)(Yo,2),$o=Zo[0],Xo=Zo[1],ea=(0,i.useState)(null),ta=(0,a.A)(ea,2),na=ta[0],ra=ta[1],oa=(0,i.useState)(""),aa=(0,a.A)(oa,2),ia=aa[0],sa=aa[1],ga=(0,i.useState)(null),ha=(0,a.A)(ga,2),fa=ha[0],ba=ha[1],wa=(0,i.useState)(!1),ka=(0,a.A)(wa,2),Aa=ka[0],ja=ka[1],Ca=(0,i.useMemo)(()=>(0,ae.Nn)(null===na||void 0===na?void 0:na.doc,{isGlobalView:!(null===na||void 0===na||!na.isGlobalView)}),[na]),Ea=(0,i.useState)(!1),Da=(0,a.A)(Ea,2),Ta=Da[0],Ra=Da[1],Oa=(0,i.useState)(!1),Fa=(0,a.A)(Oa,2),La=Fa[0],_a=Fa[1],Ua=(0,i.useState)(!1),Ma=(0,a.A)(Ua,2),za=Ma[0],Ba=Ma[1],Wa=(0,i.useState)(!1),Ja=(0,a.A)(Wa,2),qa=Ja[0],Ha=Ja[1],Ga=(0,i.useState)(!1),Ka=(0,a.A)(Ga,2),fi=Ka[0],Ai=Ka[1],ji=(0,i.useState)(null),Ni=(0,a.A)(ji,2),Ci=(Ni[0],Ni[1],(0,i.use
1State)(!1)),Si=(0,a.A)(Ci,2),Ei=Si[0],Ii=Si[1],Di=(0,i.useCallback)(e=>{const t=Array.isArray(null===e||void 0===e?void 0:e.workspaceIds)?e.workspaceIds.map(e=>String(e)).filter(Boolean):[];if(0===t.length)return;const n=Lo?String("string"===typeof Lo?Lo:Lo.id||Lo._id||Lo.workspaceId||""):null;if(n&&t.includes(n)&&"global"!==zo)return;const r=new Set((Or||[]).map(e=>String(e.id))),o=t.find(e=>r.has(e))||t[0];o&&(Ii(!0),_o(o),Bo("workspace"))},[Lo,zo,Or]),Pi=(0,i.useRef)(!1),Ti=(0,i.useState)(null),Ri=(0,a.A)(Ti,2),Oi=Ri[0],Fi=Ri[1],Li=(0,i.useState)(!1),_i=(0,a.A)(Li,2),Ui=_i[0],Mi=_i[1],zi=(0,i.useState)(""),Bi=(0,a.A)(zi,2),Wi=Bi[0],Vi=Bi[1],Ji=(0,i.useState)(null),qi=(0,a.A)(Ji,2),Hi=qi[0],Gi=qi[1],Ki=(0,i.useRef)(!1),Qi=function(e,t,n){const r=(0,i.useState)(!1),o=(0,a.A)(r,2),s=o[0],l=o[1],d=(0,i.useState)(!1),c=(0,a.A)(d,2),u=c[0],m=c[1],p=(0,i.useState)(!1),g=(0,a.A)(p,2),h=g[0],f=g[1],y=(0,i.useState)(!1),v=(0,a.A)(y,2),x=v[0],b=v[1],w=(0,i.useState)(!1),k=(0,a.A)(w,2),A=k[0],j=k[1],N=(0,i.useState)(!1),C=(0,a.A)(N,2),S=C[0],E=C[1],I=(0,i.useState)(!1),D=(0,a.A)(I,2),P=D[0],T=D[1],R=(0,i.useState)(!1),O=(0,a.A)(R,2),F=O[0],L=O[1],_=(0,i.useState)(!1),U=(0,a.A)(_,2),M=U[0],z=U[1],B=(0,i.useState)(!1),V=(0,a.A)(B,2),J=V[0],q=V[1],H=(0,i.useState)("sop"),G=(0,a.A)(H,2),K=G[0],Q=G[1],Y=(0,i.useState)(""),Z=(0,a.A)(Y,2),$=Z[0],X=Z[1],te=(0,i.useState)(!1),ne=(0,a.A)(te,2),re=ne[0],oe=ne[1],ae=(0,i.useState)(!1),ie=(0,a.A)(ae,2),se=ie[0],le=ie[1],de=(0,i.useState)(!1),ce=(0,a.A)(de,2),ue=ce[0],me=ce[1],pe=(0,i.useState)(!1),he=(0,a.A)(pe,2),fe=he[0],ye=he[1],ve=(0,i.useState)(!1),xe=(0,a.A)(ve,2),be=xe[0],we=xe[1],ke=(0,i.useState)(!1),Ae=(0,a.A)(ke,2),je=Ae[0],Ne=Ae[1],Ce=(0,i.useState)(!1),Se=(0,a.A)(Ce,2),Ee=Se[0],Ie=Se[1],De=(0,i.useState)(null),Te=(0,a.A)(De,2),Re=Te[0],Oe=Te[1],Fe=(0,Pe.getSelectedOrganizationId)()||t||n;return(0,i.useEffect)(()=>{const t=async()=>{if(!Fe||null===e||void 0===e||!e.uid)return(0,ee.dO)(),l(!1),void m(!0);m(!1);try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getVersionControlIntegrationStatus"),r=!0===(null===(t=(await n({organizationId:Fe})).data)||void 0===t?void 0:t.enabled);l(r),(0,ee.cx)(Fe,r)}catch(n){console.error("Error fetching version control integration status:",n),l(!1),(0,ee.cx)(Fe,!1)}finally{m(!0)}};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getTimerIntegrationStatus"),r=await n({organizationId:Fe});f(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching timer integration status:",n),f(!1)}else f(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getMascotIntegrationStatus"),r=await n({organizationId:Fe});b(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching mascot integration status:",n),b(!1)}else b(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getPdfExportIntegrationStatus"),r=await n({organizationId:Fe});j(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching PDF export integration status:",n),j(!1)}else j(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getDocumentSignaturesIntegrationStatus"),r=await n({organizationId:Fe});E(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Document signatures integration status:",n),E(!1)}else E(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>
1{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getDocumentLockIntegrationStatus"),r=await n({organizationId:Fe});T(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Document lock integration status:",n),T(!1)}else T(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getAutoTitleIntegrationStatus"),r=await n({organizationId:Fe});L(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Auto title integration status:",n),L(!1)}else L(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getAutoCategoryIntegrationStatus"),r=await n({organizationId:Fe});z(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Auto category integration status:",n),z(!1)}else z(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(!Fe||null===e||void 0===e||!e.uid)return q(!1),Q("sop"),void X("");try{var t,n,r;const e=(0,ge.getFunctions)(),o=(0,ge.httpsCallable)(e,"getSopEnhancementIntegrationStatus"),a=await o({organizationId:Fe});q(!0===(null===(t=a.data)||void 0===t?void 0:t.enabled)),Q((null===(n=a.data)||void 0===n?void 0:n.enhancementGoal)||"sop"),X((null===(r=a.data)||void 0===r?void 0:r.customGoalDescription)||"")}catch(o){console.error("Error fetching SOP enhancement integration status:",o),q(!1),Q("sop"),X("")}};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getVoiceIntegrationStatus"),r=await n({organizationId:Fe});oe(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Voice integration status:",n),oe(!1)}else oe(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getPexelsIntegrationStatus"),r=await n({organizationId:Fe});le(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Pexels integration status:",n),le(!1)}else le(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getFormsIntegrationStatus"),r=await n({organizationId:Fe});me(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Forms integration status:",n),me(!1)}else me(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getTemplateFillIntegrationStatus"),r=await n({organizationId:Fe});ye(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Template Fill integration status:",n),ye(!1)}else ye(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>
1{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getEnvVaultIntegrationStatus"),r=await n({organizationId:Fe});we(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Env Vault integration status:",n),we(!1)}else we(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const t=async()=>{if(Fe&&null!==e&&void 0!==e&&e.uid)try{var t;const e=(0,ge.getFunctions)(),n=(0,ge.httpsCallable)(e,"getEmailToDocumentIntegrationStatus"),r=await n({organizationId:Fe});Ne(!0===(null===(t=r.data)||void 0===t?void 0:t.enabled))}catch(n){console.error("Error fetching Email to Document integration status:",n),Ne(!1)}else Ne(!1)};t();const n=()=>t();return window.addEventListener("organizationChanged",n),()=>window.removeEventListener("organizationChanged",n)},[null===e||void 0===e?void 0:e.uid,t,n]),(0,i.useEffect)(()=>{const r=async()=>{if(!Fe||null===e||void 0===e||!e.uid)return(0,W.gg)("[Stripe feature flags] skipped status fetch",{orgId:Fe,selectedOrganizationId:(0,Pe.getSelectedOrganizationId)(),organizationId:t,currentOrganizationId:n,hasUser:!(null===e||void 0===e||!e.uid)}),Ie(!1),void Oe(null);try{var r,o,a,i,s,l,d;const e=(0,ge.getFunctions)(),c=(0,ge.httpsCallable)(e,"getStripeIntegrationStatus");(0,W.gg)("[Stripe feature flags] fetching status",{orgId:Fe,selectedOrganizationId:(0,Pe.getSelectedOrganizationId)(),organizationId:t,currentOrganizationId:n});const u=await c({organizationId:Fe});(0,W.gg)("[Stripe feature flags] status response",{orgId:Fe,connected:!0===(null===(r=u.data)||void 0===r?void 0:r.connected),hourlyRate:null!==(o=null===(a=u.data)||void 0===a?void 0:a.hourlyRate)&&void 0!==o?o:null,hasHourlyRate:null!=(null===(i=u.data)||void 0===i?void 0:i.hourlyRate)}),Ie(!0===(null===(s=u.data)||void 0===s?void 0:s.connected)),Oe(null!==(l=null===(d=u.data)||void 0===d?void 0:d.hourlyRate)&&void 0!==l?l:null)}catch(c){console.error("Error fetching Stripe integration status:",c),(0,W.gg)("[Stripe feature flags] status fetch failed",{orgId:Fe,errorMessage:null===c||void 0===c?void 0:c.message,errorCode:null===c||void 0===c?void 0:c.code}),Ie(!1),Oe(null)}};r();const o=()=>r();return window.addEventListener("organizationChanged",o),()=>window.removeEventListener("organizationChanged",o)},[null===e||void 0===e?void 0:e.uid,t,n]),{versionControlEnabled:s,versionControlReady:u,timerEnabled:h,pdfExportEnabled:A,documentSignaturesEnabled:S,documentLockEnabled:P,autoTitleEnabled:F,autoCategoryEnabled:M,sopEnhancementEnabled:J,enhancementGoal:K,customGoalDescription:$,voiceEnabled:re,pexelsEnabled:se,formsEnabled:ue,templateFillEnabled:fe,envVaultEnabled:be,emailToDocumentEnabled:je,stripeIntegrationConnected:Ee,stripeHourlyRate:Re,mascotEnabled:x}}(X,ue,ye),Yi=Qi.versionControlEnabled,Zi=Qi.versionControlReady,$i=Qi.timerEnabled,Xi=Qi.pdfExportEnabled,es=Qi.documentSignaturesEnabled,ts=Qi.documentLockEnabled,ns=Qi.autoTitleEnabled,rs=Qi.sopEnhancementEnabled,os=Qi.voiceEnabled,as=Qi.pexelsEnabled,is=Qi.formsEnabled,ss=Qi.templateFillEnabled,ls=Qi.envVaultEnabled,ds=Qi.stripeIntegrationConnected,cs=Qi.stripeHourlyRate,us=Qi.mascotEnabled,ms=(0,i.useCallback)(()=>{Tt("")},[]);(0,i.useEffect)(()=>{const e=Nt.current;if(null===e||void 0===e||!e.taskName||null===Ve||void 0===Ve||!Ve.startsWith("new_"))return;if(!$i)return;Nt.current=null;const t=setTimeout(()=>{Tt(e.taskName)},800);return()=>clearTimeout(t)},[Ve,$i]);const ps=Sa(ye||ue||null,"global"===zo?null:"string"===typeof Lo?Lo:null).presets,gs=(0,i.useState)(!1),hs=(0,a.A)(gs,2),fs=hs[0],ys=hs[1],vs=(0,i.useState)(!1),xs=(0,a.A)(vs,2),bs=xs[0],ws=xs[1],ks=(0,i.useState)(null),As=(0,a.A)(ks,2),js=As[0],Ns=As[1],Cs=(0,i.useRef)(null),Ss=(0,i.useRef)(null),Es=(0,i.useRef)(null),Is=(0,i.useState)(!1),Ds=(0,a.A)(Is,2),Ps=Ds[0],Ts=Ds[1],Rs=(0,i.useRef)(!1),Os=(0,i.useState)(!1),Fs=(0,a.A)(Os,2),Ls=Fs[0],_s=Fs[1],Us=(0,i.useState)(null),Ms=(0,a.A)(Us,2),zs=Ms[0],Bs=Ms[1],Ws=(0,i.useState)(null),Vs=(0,a.A)(Ws,2),Js=Vs[0],qs=Vs[1];(0,i.useEffect)(()=>{Rs.current=fs},[fs]);const Hs=(0,i.useRef)(new Set),Gs=(0,i.useRef)(null),Ks=(0,i.useRef)(new Map),Qs=(0,i.useRef)(null),Ys=(0,i.useRef)(new Map),Zs=(0,i.useRef)(!1),$s=(0,i.useState)(!1),Xs=(0,a.A)($s,2),el=Xs[0],tl=Xs[1],nl=(0,i.useState)(null),rl=(0,a.A)(nl,2),ol=rl[0],al=rl[1],il=(0,i.useState)(null),sl=(0,a.A)(il,2),ll=sl[0],dl=sl[1],cl=(0,i.useState)(null),ul=(0,a.A)(cl,2),ml=ul[0],pl=ul[1],gl=(0,i.useState)(null),hl=(0,a.A)(gl,2),fl=hl[0],yl=hl[1],vl=(0,i.useState)(null),xl=(0,a.A)(vl,2),bl=xl[0],wl=xl[1],kl=(0,i.useState)(()=>new Set),Al=(0,a.A)(kl,2),jl=Al[0],Nl=Al[1],Cl=(0,i.useState)(null),Sl=(0,a.A)(Cl,2),El=Sl[0],Il=Sl[1],Dl=(0,i.useState)(null),Pl=(0,a.A)(Dl,2),Tl=Pl[0],Rl=Pl[1],Ol=(0,i.useState)(!1),Fl=(0,a.A)(Ol,2),Ll=Fl[0],_l=Fl[1],Ul=(0,i.useState)(!1),Ml=(0,a.A)(Ul,2),zl=Ml[0],Bl=Ml[1],Wl=(0,i.useState)(""),Vl=(0,a.A)(Wl,2),Jl=Vl[0],ql=Vl[1],Hl=(0,i.useState)(!1),Gl=(0,a.A)(Hl,2),Kl=Gl[0],Ql=Gl[1],Yl=(0,i.useState)(!1),Zl=(0,a.A)(Yl,2),$l=Zl[0],Xl=Zl[1],ed=(0,i.useState)(!1),td=(0,a.A)(ed,2),nd=td[0],rd=td[1],od=(0,i.useState)(""),ad=(0,a.A)(od,2),id=ad[0],sd=ad[1],ld=(0,i.useRef)(null),dd=(0,i.useRef)(null),cd=(0,i.useRef)(null),ud=(0,i.useState)(!1),md=(0,a.A)(ud,2),pd=md[0],gd=md[1],hd=(0,i.useRef)(null),fd=(0,i.useRef)(null),yd=(0,i.useState)(null),vd=(0,a.A)(yd,2),xd=vd[0],bd=vd[1],wd=(0,i.useState)({}),kd=(0,a.A)(wd,2),Ad=kd[0],jd=kd[1],Nd=(0,i.useState)(null),Cd=(0,a.A)(Nd,2),Sd=Cd[0],Ed=Cd[1],Id=(0,i.useState)(""),Dd=(0,a.A)(Id,2),Pd=Dd[0],Td=Dd[1],Rd=(0,i.useState)(null),Od=(0,a.A)(Rd,2),Fd=Od[0],Ld=Od[1],_d=(0,i.useRef)({}),Ud=(0,i.useCallback)(async e=>{if(e){Ed(e),Td(""),Ld(null);try{await(0,Jn.p4)({workspaceId:e,onDelta:e=>Td(t=>t+e),onComplete:t=>{const n={summary:(0,lo.V)(t.summary||""),docCount:"number"===typeof t.docCount?t.docCount:0,generatedAt:t.generatedAt||Date.now()};jd(t=>(0,o.A)((0,o.A)({},t),{},{[e]:n})),Fr(t=>t.map(t=>
1t.id===e?(0,o.A)((0,o.A)({},t),{},{aiOverview:n}):t)),bd(t=>t&&t.id===e?(0,o.A)((0,o.A)({},t),{},{aiOverview:n}):t),window.dispatchEvent(new CustomEvent("workspacePropertyUpdated",{detail:{workspaceId:e,updates:{aiOverview:n}}}))}})}catch(t){console.error("Error streaming workspace overview:",t),Ld((null===t||void 0===t?void 0:t.message)||"Could not generate overview. Please try again.")}finally{Ed(null),Td("")}}},[]);(0,i.useEffect)(()=>{if("global"===zo||!Lo)return;if(Sd)return;const e=Or.find(e=>e.id===Lo),t=Ad[Lo]||(null===e||void 0===e?void 0:e.aiOverview)||null;if(t&&t.summary)return;0!==((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).filter(e=>Array.isArray(e.workspaceIds)&&e.workspaceIds.some(e=>String(e)===String(Lo))).length&&(_d.current[Lo]||(_d.current[Lo]=!0,Ud(Lo)))},[zo,Lo,Or,Ad,Pn,Sd,Ud]);const Md=(0,i.useState)(!1),zd=(0,a.A)(Md,2),Bd=zd[0],Wd=zd[1],Vd=(0,i.useState)(!1),Jd=(0,a.A)(Vd,2),qd=Jd[0],Hd=Jd[1],Gd=(0,i.useState)(!1),Kd=(0,a.A)(Gd,2),Qd=Kd[0],Yd=Kd[1],Zd=(0,i.useState)(0),$d=(0,a.A)(Zd,2),Xd=$d[0],ec=$d[1],tc=(0,i.useState)(!1),nc=(0,a.A)(tc,2),rc=nc[0],oc=nc[1],ac=(0,i.useState)([]),ic=(0,a.A)(ac,2),sc=ic[0],lc=ic[1],dc=(0,i.useMemo)(()=>{var e,t;if(!Array.isArray(sc)||0===sc.length)return null;return null!==(e=null===(t=[...sc].sort((e,t)=>{var n,r,o,a,i,s,l,d;const c=null!==(n=null===(r=e.createdAt)||void 0===r||null===(o=r.toMillis)||void 0===o?void 0:o.call(r))&&void 0!==n?n:null!=(null===(a=e.createdAt)||void 0===a?void 0:a.seconds)?1e3*e.createdAt.seconds:0,u=null!==(i=null===(s=t.createdAt)||void 0===s||null===(l=s.toMillis)||void 0===l?void 0:l.call(s))&&void 0!==i?i:null!=(null===(d=t.createdAt)||void 0===d?void 0:d.seconds)?1e3*t.createdAt.seconds:0;return c!==u?c-u:String(e.id||"").localeCompare(String(t.id||""))})[0])||void 0===t?void 0:t.id)&&void 0!==e?e:null},[sc]),cc=(0,i.useState)(null),uc=(0,a.A)(cc,2),mc=uc[0],pc=uc[1],gc=(0,i.useState)(!1),hc=(0,a.A)(gc,2),fc=hc[0],yc=hc[1],vc=(0,i.useState)(0),xc=(0,a.A)(vc,2),bc=xc[0],wc=xc[1];(0,i.useEffect)(()=>{Ve||Hd(!1)},[Ve]);const kc=(0,i.useState)(!1),Ac=(0,a.A)(kc,2),jc=Ac[0],Nc=Ac[1],Cc=(0,i.useState)(!1),Sc=(0,a.A)(Cc,2),Ec=(Sc[0],Sc[1],(0,i.useRef)(null)),Ic=(0,i.useRef)(null),Dc=(0,i.useState)({left:0,top:0}),Pc=(0,a.A)(Dc,2),Tc=Pc[0],Rc=Pc[1],Oc=(0,i.useRef)(null),Fc=(0,i.useState)({left:0,top:0,right:0}),Lc=(0,a.A)(Fc,2),_c=Lc[0],Uc=Lc[1],Mc=()=>{Wd(e=>{const t=!e;return t&&(Yd(!1),ec(e=>e+1)),t})};(0,i.useEffect)(()=>{"brainMap"!==dn&&(Yd(!1),ec(e=>e+1))},[dn]),(0,i.useEffect)(()=>{De(Or)},[Or,De]),(0,i.useEffect)(()=>{Te(Bd)},[Bd,Te]),(0,i.useEffect)(()=>{Ee(xd)},[xd,Ee]),(0,i.useEffect)(()=>{if(null===xd||void 0===xd||!xd.id)return void lc([]);const e=(0,B.P)((0,B.rJ)(G.db,"externalAgents"),(0,B._M)("workspaceId","==",xd.id));return(0,B.aQ)(e,e=>{lc(e.docs.map(e=>(0,o.A)({id:e.id},e.data())))},e=>{console.error("Error listening to externalAgents:",e),setTimeout(()=>wc(e=>e+1),3e3)})},[null===xd||void 0===xd?void 0:xd.id,bc]),(0,i.useEffect)(()=>{if(null===xd||void 0===xd||!xd.id)return void Nu([]);const e=(0,B.P)((0,B.rJ)(G.db,"shareableLinks"),(0,B._M)("workspaceId","==",xd.id));return(0,B.aQ)(e,e=>{const t=e.docs.map(e=>(0,o.A)({id:e.id},e.data())).filter(e=>!e.documentId);t.sort((e,t)=>{const n=e=>{var t;return(null===e||void 0===e||null===(t=e.toMillis)||void 0===t?void 0:t.call(e))||(e instanceof Date?e.getTime():0)};return n(t.createdAt)-n(e.createdAt)}),Nu(t)},e=>{console.error("Error listening to workspace share links:",e)})},[null===xd||void 0===xd?void 0:xd.id]);const zc=(0,i.useState)(!0),Bc=(0,a.A)(zc,1)[0],Wc=(0,i.useState)(!1),Vc=(0,a.A)(Wc,2),Jc=Vc[0],qc=Vc[1],Hc=(0,i.useRef)(null),Gc=(0,i.useState)(!1),Kc=(0,a.A)(Gc,2),Qc=Kc[0],Yc=Kc[1],Zc=(0,i.useRef)(null),$c=(0,i.useState)(!1),Xc=(0,a.A)($c,2),eu=Xc[0],tu=Xc[1],nu=(0,i.useCallback)(e=>{tu(t=>t===e?t:e)},[]),ru=(0,i.useMemo)(()=>Ve?ar?(0,o.A)((0,o.A)({},ar),{},{id:Ve,isNew:Boolean(null===Ve||void 0===Ve?void 0:Ve.startsWith("new_")),workspace:ar.workspace||ar.workspaceName||"Default"}):{id:Ve,isNew:Boolean(null===Ve||void 0===Ve?void 0:Ve.startsWith("new_")),workspace:"Default"}:null,[ar,Ve]);(0,i.useEffect)(()=>
1{if(Ve){tu(!1);const e=Zc.current;e&&requestAnimationFrame(()=>{e.scrollTop=0})}},[Ve]),Yr({docId:Ve&&!String(Ve).startsWith("new_")?Ve:null,enabled:Boolean(Ve&&(null===(e=G.j2.currentUser)||void 0===e?void 0:e.uid)&&!String(Ve).startsWith("new_")),scrollContainerRef:Zc});(0,i.useRef)(null);const ou=(0,i.useState)(null),au=(0,a.A)(ou,2),iu=(au[0],au[1]),su=(0,i.useRef)(null),lu=(0,i.useRef)(!1),du=(0,i.useRef)(!1),cu=(0,i.useRef)(null),uu=(0,i.useState)(null),mu=(0,a.A)(uu,2),pu=mu[0],gu=mu[1],hu=(0,i.useRef)(null),fu=(0,i.useRef)(null);(0,i.useEffect)(()=>()=>{fu.current&&clearTimeout(fu.current)},[]);const yu=(0,i.useRef)(null),vu=(0,i.useState)(!1),xu=(0,a.A)(vu,2),bu=xu[0],wu=xu[1],ku=(0,i.useState)([]),Au=(0,a.A)(ku,2),ju=Au[0],Nu=Au[1],Cu=(0,i.useState)(null),Su=(0,a.A)(Cu,2),Eu=Su[0],Iu=Su[1],Du=(0,i.useState)(null),Pu=(0,a.A)(Du,2),Tu=Pu[0],Ru=Pu[1],Ou=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:[];const n=(0,i.useMemo)(()=>{if(!e||!Array.isArray(t))return 0;const n=String(e);return t.filter(e=>Array.isArray(e.workspaceIds)&&e.workspaceIds.some(e=>String(e)===n)).length},[e,t]),r=(0,i.useState)(!1),o=(0,a.A)(r,2),s=o[0],l=o[1],d=(0,i.useState)(null),c=(0,a.A)(d,2),u=c[0],m=c[1],p=(0,i.useState)(!1),g=(0,a.A)(p,2),h=g[0],f=g[1],y=(0,i.useCallback)(function(){0!==n?(uo("Share button clicked, forcePublic:"),m(null),l(!0)):Ie.Ay.error("You need to add at least one document before sharing this workspace.",{duration:4e3})},[n]),v=(0,i.useCallback)(e=>{uo("Document share button clicked, documentId:"),m(e),l(!0)},[]),x=(0,i.useCallback)(()=>{uo("handleCloseShareModal called"),l(!1),m(null)},[]),b=(0,i.useCallback)(async e=>{try{uo("\ud83d\udd35 handleShareModalSave received:"),uo("\u2705 Share modal settings persisted (modal stays open until user closes)")}catch(t){console.error("Error saving share settings:",t);const e=t.message||"Failed to save sharing settings";e.includes("permission")||e.includes("Permission")?Ie.Ay.error("Missing or insufficient permissions. Please check your access to this workspace.",{duration:5e3}):Ie.Ay.error("Failed to save sharing settings: ".concat(e),{duration:4e3})}},[]);return{shareModalOpen:s,setShareModalOpen:l,documentShareId:u,shareMenuOpen:h,setShareMenuOpen:f,handleOpenShareModal:y,handleOpenDocumentShareModal:v,handleCloseShareModal:x,handleShareModalSave:b}}(Lo,Pn.documents),Fu=Ou.shareModalOpen,Lu=Ou.setShareModalOpen,_u=Ou.documentShareId,Uu=Ou.shareMenuOpen,Mu=Ou.setShareMenuOpen,zu=Ou.handleOpenShareModal,Bu=Ou.handleOpenDocumentShareModal,Wu=Ou.handleCloseShareModal,Vu=Ou.handleShareModalSave,Ju=(0,i.useMemo)(()=>{var e;return Eu?{isPublic:Eu.isPublic,linkId:Eu.linkId,expiryDate:Eu.expiryDate,agentConfig:Eu.agentConfig,emailNotifications:Eu.emailNotifications,enabledViews:Eu.enabledViews||"traditional",shareAsReport:!0===Eu.shareAsReport,reportIntroduction:Eu.reportIntroduction||"",reportCoverButtonColor:Eu.reportCoverButtonColor||"",sharedDocumentIds:Eu.sharedDocumentIds||null,linkLabel:Eu.linkLabel||"",commentsEnabled:!0===Eu.commentsEnabled,shareBranding:null!==(e=Eu.shareBranding)&&void 0!==e?e:null,mascotMode:!0===Eu.mascotMode}:null},[Eu]),qu=(0,i.useCallback)(e=>{Iu(e),zu(!1)},[zu]),Hu=(0,i.useCallback)(()=>{Iu(null),zu(!1)},[zu]),Gu=(0,i.useCallback)(async e=>{try{await(0,B.kd)((0,B.doc)(G.db,"shareableLinks",e.id)),Ie.Ay.success("Share link deleted")}catch(t){console.error("Error deleting share link:",t),Ie.Ay.error("Failed to delete share link")}},[]),Ku=(0,i.useCallback)(e=>{const t="".concat(window.location.origin,"/shared/").concat(e.linkId);navigator.clipboard.writeText(t).then(()=>{Ru(e.id),setTimeout(()=>Ru(null),2e3)}).catch(e=>console.error("Failed to copy:",e))},[]),Qu=(0,i.useCallback)(e=>{if(!e)return"";let t;return"function"===typeof(null===e||void 0===e?void 0:e.toDate)?t=e.toDate():"function"===typeof(null===e||void 0===e?void 0:e.toMillis)?t=new Date(e.toMillis()):e instanceof Date?t=e:"number"===typeof e||"string"===typeof e?t=new Date(e):null!=(null===e||void 0===e?void 0:e.seconds)&&(t=new Date(1e3*e.seconds)),!t||Number.isNaN(t.getTime())?"":t.toLocaleStr
1ing(void 0,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})},[]),Yu=(0,i.useCallback)(()=>{Wu(),Iu(null)},[Wu]);(0,i.useEffect)(()=>{(0,W.gg)("\ud83d\udfe1 shareModalOpen changed to:",Fu)},[Fu]);const Zu=vo({currentUser:Z,currentPage:Ve,setKnowledgeBase:Rn,setCurrentDoc:ir,currentDoc:ar}),$u=Zu.paymentConfigOpen,Xu=Zu.setPaymentConfigOpen,em=Zu.paymentConfigUpdating,tm=Zu.paymentFixedAmountEditing,nm=Zu.setPaymentFixedAmountEditing,rm=Zu.paymentSubscriptionAmountEditing,om=Zu.setPaymentSubscriptionAmountEditing,am=Zu.paymentConfigUpdateInProgressRef,im=Zu.lastPaymentUpdateAtRef,sm=Zu.lastPaymentEnabledOnAtRef,lm=Zu.lastPaymentSubscriptionEnabledOnAtRef,dm=Zu.paymentSubscriptionEnabledEffective,cm=Zu.paymentButtonRef,um=(Zu.lastPaymentDropdownOpenAtRef,Zu.updateDocumentPaymentConfig),mm=(0,i.useRef)(null),pm=(0,i.useRef)(null),gm=(0,i.useRef)(null),hm=(0,i.useState)(!1),fm=(0,a.A)(hm,2),ym=fm[0],vm=fm[1],xm=(0,i.useState)(""),bm=(0,a.A)(xm,2),wm=bm[0],km=bm[1],Am=(0,i.useState)("form"),jm=(0,a.A)(Am,2),Nm=jm[0],Cm=jm[1],Sm=(0,i.useState)(!1),Em=(0,a.A)(Sm,2),Im=Em[0],Dm=Em[1],Pm=(0,i.useState)(""),Tm=(0,a.A)(Pm,2),Rm=Tm[0],Om=Tm[1],Fm=(0,i.useState)([]),Lm=(0,a.A)(Fm,2),_m=Lm[0],Um=Lm[1],Mm=(0,i.useRef)(null),zm=(0,i.useRef)(null),Bm=(0,i.useRef)([]),Wm=(0,i.useState)([]),Vm=(0,a.A)(Wm,2),Jm=Vm[0],qm=Vm[1],Hm=(0,i.useState)(null),Gm=(0,a.A)(Hm,2),Km=Gm[0],Qm=Gm[1],Ym=(0,i.useState)(null),Zm=(0,a.A)(Ym,2),$m=Zm[0],Xm=Zm[1],ep=(0,i.useState)(!1),tp=(0,a.A)(ep,2),np=tp[0],rp=tp[1],op=(0,i.useState)(!1),ap=(0,a.A)(op,2),ip=ap[0],sp=ap[1],lp=(0,i.useRef)(!1),dp=(0,i.useState)(!1),cp=(0,a.A)(dp,2),up=cp[0],mp=cp[1],pp=(0,i.useState)("form"),gp=(0,a.A)(pp,2),hp=gp[0],fp=gp[1],yp=(0,i.useState)(!1),vp=(0,a.A)(yp,2),xp=vp[0],bp=vp[1],wp=(0,i.useState)(""),kp=(0,a.A)(wp,2),Ap=kp[0],jp=kp[1],Np=(0,i.useState)([]),Cp=(0,a.A)(Np,2),Sp=Cp[0],Ep=Cp[1],Ip=(0,i.useState)(0),Dp=(0,a.A)(Ip,2),Pp=Dp[0],Tp=Dp[1],Rp=(0,i.useRef)(null),Op=(0,i.useMemo)(()=>{const e=null===ar||void 0===ar?void 0:ar.lastAIGenerateOptions;return e?{documentType:e.documentType||"auto",tone:e.tone||"professional",useCompanyInfo:!1!==e.useCompanyInfo,useWorkspaceDocuments:!0===e.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(e.pinnedDocumentIds)?e.pinnedDocumentIds:[]}:{documentType:"auto",tone:"professional",useCompanyInfo:!0,useWorkspaceDocuments:!0,pinnedDocumentIds:[]}},[null===ar||void 0===ar?void 0:ar.lastAIGenerateOptions]),Fp=(0,i.useCallback)(e=>{var t;const n=null===(t=sr.current)||void 0===t?void 0:t.lastAIGenerateOptions,r=String(e||"").trim();return n?{userPrompt:r,documentType:n.documentType||"auto",tone:n.tone||"professional",useCompanyInfo:!1!==n.useCompanyInfo,useWorkspaceDocuments:!0===n.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(n.pinnedDocumentIds)?n.pinnedDocumentIds:[],askClarification:!1}:{userPrompt:r,documentType:"auto",tone:"professional",useCompanyInfo:!0,useWorkspaceDocuments:!0,pinnedDocumentIds:[],askClarification:!1}},[]),Lp=(0,i.useState)(""),_p=(0,a.A)(Lp,2),Up=_p[0],Mp=_p[1],zp=(0,i.useMemo)(()=>{const e=Mm.current;return"integrations"===Nm&&!!e&&Jm.includes("documentSignatures")&&!!Km&&(0,Pr.Jm)(Km,"documentSignatures")&&"unsure"===(0,Tr.K1)(e.userPrompt,e.documentType)},[Nm,Jm,Km]),Bp=(0,i.useMemo)(()=>{let e=[];
1if(Lo&&"global"!==zo){const t=String(Lo);e=Pn.documents.filter(e=>{if(!Array.isArray(e.workspaceIds))return!1;const n=e.workspaceIds.some(e=>null===e||void 0===e?"Default"===t:String(e)===t),r=Or.some(e=>e.id===t);return n&&r}),e=Array.from(new Map(e.map(e=>[e.id,e])).values())}return e},[Lo,zo,Pn.documents,Or]),Wp=(0,i.useMemo)(()=>{if(!Array.isArray(Bp)||!Bp.length)return[];const e=null!=Ve?String(Ve):null;return Bp.filter(e=>e&&e.id).filter(t=>!e||String(t.id)!==e).map(e=>({id:e.id,title:(0,_e.Od)(e,"Untitled")}))},[Bp,Ve]);(0,i.useEffect)(()=>{var e;if(!Ve)return ir(null),Qs.current=null,vg(null),wg(!1),void Ys.current.clear();if(null===(e=G.j2.currentUser)||void 0===e||!e.uid)return void(0,W.gg)("\u23f8\ufe0f Skipping document listener: no authenticated user yet");if(vg(null),wg(!1),Ve.startsWith("new_"))return void(Qs.current=Ve);Ks.current.get(Ve)||Qs.current===Ve||(Qs.current=Ve);const t=ie.isJustCreated(Ve),n=(null===ar||void 0===ar?void 0:ar.id)&&ar.id!==Ve;!t&&n?mr(!0):t||ar||mr(!0);const r=(0,B.aQ)((0,B.doc)(G.db,"knowledgeBaseDocuments",Ve),e=>{if(e.exists()){var t,n;const r=(0,o.A)((0,o.A)({},e.data()),{},{id:e.id}),a=(r.restoredFromVersion&&r.restoredAt,Date.now()),i=(null===(t=r.restoredAt)||void 0===t||null===(n=t.toMillis)||void 0===n?void 0:n.call(t))||(r.restoredAt instanceof Date?r.restoredAt.getTime():null),s=i&&a-i<5e3;if(ie.shouldSkipSnapshot(Ve)||s)return void(0,W.gg)("\u23ed\ufe0f Skipping onSnapshot update - recent local save, just created, or version restore detected");const l=Ys.current.get(Ve),d=ur&&!l;ir(e=>{const t=Math.max(sm.current,fo()),n=Math.max(lm.current,yo()),a=Date.now()-t<1e4,i=Date.now()-n<1e4;if(!1!==r.paymentEnabled||!0!==(null===e||void 0===e?void 0:e.paymentEnabled)&&!a||(0,W.gg)("[Payment] Snapshot has paymentEnabled false \u2013 will guard or fix",{hasPrev:!!e,prevPayment:null===e||void 0===e?void 0:e.paymentEnabled,recentlyTurnedOn:a}),am.current)return(0,W.gg)("[Payment] Snapshot SKIP: paymentConfigUpdateInProgressRef"),mr(!1),e;if(!0===(null===e||void 0===e?void 0:e.paymentEnabled)&&!1===r.paymentEnabled&&Date.now()-im.current<2e3)return(0,W.gg)("[Payment] Snapshot SKIP: 2s guard (stale paymentEnabled false)",{lastUpdateAgo:Date.now()-im.current}),mr(!1),e;if((!0===(null===e||void 0===e?void 0:e.paymentSubscriptionEnabled)||i)&&!1===r.paymentSubscriptionEnabled&&(Date.now()-im.current<1e4||i))return(0,W.gg)("[Payment] Snapshot SKIP: subscription guard (stale paymentSubscriptionEnabled false)",{lastUpdateAgo:Date.now()-im.current,recentlyTurnedSubscriptionOn:i}),mr(!1),e;if((0,W.v4)("\ud83d\udcf1 onSnapshot fired",{currentPage:Ve,prevId:null===e||void 0===e?void 0:e.id,prevHasEditorJson:!(null===e||void 0===e||!e.editorJson),dataId:r.id,dataIsEncrypted:r.isEncrypted,dataHasEditorJson:!!r.editorJson,isInitialLoad:d,documentLoading:ur}),e&&e.id===Ve&&e.editorJson,!e){if(r.isEncrypted)return d?((0,W.gg)("\ud83d\udd12 Skipping onSnapshot initial set for encrypted document - getCurrentDocument() still in progress"),e):((0,W.gg)("\ud83d\udd12 Skipping onSnapshot initial set for encrypted document - getCurrentDocument() will handle decryption"),e);if(!d){mr(!1);const e=(0,o.A)((0,o.A)({},r),{},{id:Ve});return!1===r.paymentEnabled&&Date.now()-t<1e4&&((0,W.gg)("[Payment] Snapshot !prev path: forcing paymentEnabled true (stale data had false)",{lastTurnOnAt:t}),e.paymentEnabled=!0),e}return e}e.editorJson&&(e.isDecrypted||e.isEncrypted);const s=e.editorJson;if(e.id===Ve&&s){if(d)return(0,W.gg)("\ud83d\udee1\ufe0f Skipping onSnapshot update during initial load - preserving document content"),e;if(!me(e,r))return mr(!1),e;const n=pe(e,r);if(!n.editorJson&&e.editorJson){const t={prevHasEditorJson:!!e.editorJson,dataIsEncrypted:r.isEncrypted,dataHasEditorJson:!!r.editorJson,mergedHasEditorJson:!!n.editorJson,currentPage:Ve,prevId:e.id};return(0,W.gg)("\ud83d\udee1\ufe0f Skipping onSnapshot update - merge would lose editorJson",t),(0,W.v4)("\ud83d\udea8 CRITICAL: Merge would lose editorJson - skipping update",t),mr(!1),e}if(n.id!==Ve)return(0,W.gg)("\ud83d\udee1\ufe0f Skipping onSnapshot update - merge would change document ID",{mergedId:n.id,currentPage:Ve,prevId:e.id}),mr(!1),e;if(!0===e.paymentEnabled&&!1===n.paymentEnabled)return(0,W.gg)("[Payment] Snapshot SKIP: prev paymentEnabled true, merged false (content path)"),mr(!1),e;if(!0===e.paymentSubscriptionEnabled&&!1===n.paymentSubscriptionEnabled)return(0,W.gg)("[Payment] Snapshot SKIP: prev paymentSubscriptionEnabled true, merged false (content path)"),mr(!1),e;!1===n.paymentEnabled&&(0,W.gg)("[Payment] Snapshot APPLYING (content path) doc with paymentEnabled false",{prevPaymentEnabled:null===e||void 0===e?void 0:e.paymentEnabled,dataPaymentEnabled:r.paymentEnabled});let a=n;return!1===n.paymentEnabled&&Date.now()-t<1e4&&((0,W.gg)("[Payment] Snapshot (content path): forcing paymentEnabled true \u2013 turned on recently"),a=(0,o.A)((0,o.A)({},n),{},{paymentEnabled:!0})),!1===n.paymentSubscriptionEnabled&&i&&((0,W.gg)("[Payment] Snapshot (content path): forcing paymentSubscriptionEnabled true \u2013 turned on recently"),a=(0,o.A)((0,o.A)({},a),{},{paymentSubscriptionEnabled:!0})),mr(!1),a}if(!me(e,r))return mr(!1),e;const l=pe(e,r);if(l.id!==Ve&&e.id===Ve)return(0,W.gg)("\ud83d\udee1\ufe0f Skipping onSnapshot update - merge would change document ID",{mergedId:l.id,currentPage:Ve,prevId:e.id}),mr(!1),e;if(!0===e.paymentEnabled&&!1===l.paymentEnabled)return(0,W.gg)("[Payment] Snapshot SKIP: prev paymentEnabled true, merged false (no-content path)"),mr(!1),e;if(!0===e.paymentSubscriptionEnabled&&!1===l.paymentSubscriptionEnabled)return(0,W.gg)("[Payment] Snapshot SKIP: prev paymentSubscriptionEnabled true, merged false (no-content path)"),mr(!1),e;!1===l.paymentEnabled&&(0,W.gg)("[Payment] Snapshot APPLYING doc with paymentEnabled false",{prevPaymentEnabled:null===e||void 0===e?void 0:e.paymentEnabled,dataPaymentEnabled:r.paymentEnabled});let c=l;return!1===l.paymentEnabled&&Date.now()-t<1e4&&((0,W.gg)("[Payment] Snapshot (no-content path): forcing paymentEnabled true \u2013 turned on recently"),c=(0,o.A)((0,o.A)({},l),{},{paymentEnabled:!0})),!1===l.paymentSubscriptionEnabled&&i&&((0,W.gg)("[Payment] Snapshot (no-content path): forcing paymentSubscriptionEnabled true \u2013 turned on recently"),c=(0,o.A)((0,o.A)({},c),{},{paymentSubscriptionEnabled:!0})),mr(!1),c}),Rn(e=>{const t=e.documents.find(e=>e.id===Ve);if(!t)return r.isEncrypted?((0,W.gg)("\ud83d\udd12 Skipping knowledgeBase update for new encrypted document - getCurrentDocument() will handle it"),e):(0,o.A)((0,o.A)({},e),{},{documents:[...e.documents,r]});if(r.isEncrypted||t.isEncrypted){(0,W.gg)("\ud83d\udd12 Updating encrypted document in knowledgeBase - preserving decrypted content");return JSON.stringify({title:t.title,category:t.category,workspaceIds:t.workspaceIds,workspace:t.workspace,updatedAt:t.updatedAt,coverImageUrl:t.coverImageUrl||null,coverImageManual:!0===t.coverImageManual,coverImagePosition:t.coverImagePosition||null,isTemplate:!0===t.isTemplate,viewerMode:t.viewerMode||null})===JSON.stringify({title:r.title,category:r.category,workspaceIds:r.workspaceIds,workspace:r.workspace,updatedAt:r.updatedAt,coverImageUrl:r.coverImageUrl||null,coverImageManual:!0===r.coverImageManual,coverImagePosition:r.coverImagePosition||null,isTemplate:!0===r.isTemplate,viewerMode:r.viewerMode||null})?e:(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===Ve?(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({},e),{},{title:r.title,category:r.category,workspaceIds:r.workspaceIds,workspace:r.workspace,updatedAt:r.updatedAt},void 0!==r.coverImageUrl&&{coverImageUrl:r.coverImageUrl}),void 0!==r.coverImageManual&&{coverImageManual:r.coverImageManual}),{},{coverImagePosition:r.coverImagePosition||null},void 0!==r.isTemplate&&{isTemplate:!0===r.isTemplate}),void 0!==r.viewerMode&&null!==r.viewerMode&&{viewerMode:r.viewerMode}),"string"===typeof r.url&&r.url?{url:r.url}:{}),"string"===typeof r.previewUrl&&r.previewUrl?{previewUrl:r.previewUrl}:{}),void 0!==r.fileName&&{fileName:r.fileName}),void 0!==r.fileType&&{fileType:r.fileType}),{},{editorJson:e.editorJson,editorHtml:e.editorHtml,textContent:e.textContent,isDecrypted:e.isDecrypted,isEncrypted:r.isEncrypted,encryptionMethod:r.encryptionMethod,userEncryptedResult:r.userEncryptedResult,workspaceEncryptedResults:r.workspaceEncryptedResults,encryptedResult:r.encryptedResult}):e)})}return JSON.stringify({title:t.title,editorJson:t.editorJson,editorHtml:t.editorHtml,category:t.category,workspaceIds:t.workspaceIds})===JSON.stringify({title:r.title,editorJson:r.editorJson,editorHtml:r.editorHtml,category:r.category,workspaceIds:r.workspaceIds})?e:(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===Ve?(0,o.A)((0,o.A)({},e),r):e)})})}},e=>{var t,n,r,o;
1if((0,W.v4)("\ud83d\udea8 onSnapshot ERROR",{currentPage:Ve,errorCode:null===e||void 0===e?void 0:e.code,errorMessage:null===e||void 0===e?void 0:e.message,errorName:null===e||void 0===e?void 0:e.name,hasCurrentDoc:!!ar,currentDocId:null===ar||void 0===ar?void 0:ar.id,currentDocHasEditorJson:!(null===ar||void 0===ar||!ar.editorJson)}),"permission-denied"===(null===e||void 0===e?void 0:e.code)||null!==e&&void 0!==e&&null!==(t=e.message)&&void 0!==t&&t.includes("Missing or insufficient permissions"))return(0,W.gg)("\u26a0\ufe0f Document listener permission denied (ignoring):",{docId:Ve,code:null===e||void 0===e?void 0:e.code,message:null===e||void 0===e?void 0:e.message}),ir(e=>e&&e.id===Ve&&(e.editorJson||"pdf"===e.viewerMode)?((0,W.v4)("\u26a0\ufe0f onSnapshot permission-denied \u2014 keeping already-loaded document",{currentPage:Ve,currentDocId:null===e||void 0===e?void 0:e.id}),e):null),void mr(!1);if((null===e||void 0===e||null===(n=e.message)||void 0===n?void 0:n.includes("transport errored"))||(null===e||void 0===e||null===(r=e.message)||void 0===r?void 0:r.includes("WebChannelConnection"))||(null===e||void 0===e||null===(o=e.message)||void 0===o?void 0:o.includes("RPC"))||"FirebaseError"===(null===e||void 0===e?void 0:e.name)&&("unavailable"===(null===e||void 0===e?void 0:e.code)||"deadline-exceeded"===(null===e||void 0===e?void 0:e.code)||"internal"===(null===e||void 0===e?void 0:e.code)))return(0,W.v4)("\ud83d\udd04 Transport error detected - preserving currentDoc",{currentPage:Ve,currentDocId:null===ar||void 0===ar?void 0:ar.id,hasEditorJson:!(null===ar||void 0===ar||!ar.editorJson),errorMessage:null===e||void 0===e?void 0:e.message}),(0,W.gg)("\u26a0\ufe0f Firestore transport error - preserving document state:",{docId:Ve,code:null===e||void 0===e?void 0:e.code,message:null===e||void 0===e?void 0:e.message,preservingCurrentDoc:!!ar}),void mr(!1);console.error("Document listener error:",e),(0,W.v4)("\u26a0\ufe0f Unknown onSnapshot error",{errorCode:null===e||void 0===e?void 0:e.code,errorMessage:null===e||void 0===e?void 0:e.message,preservingCurrentDoc:!!ar}),mr(!1)});return()=>r()},[Ve,null===X||void 0===X?void 0:X.uid]),(0,i.useEffect)(()=>{Ve&&Nc(!1)},[Ve]);const Vp=(0,i.useCallback)(async()=>{if(ar)try{qc(!0);let o={},a={},i={};try{const e=(await(0,Sn.mf)(ar.id)).filter(e=>"completed"===e.status).sort((e,t)=>{const n=e=>{var t,n,r,o,a,i,s,l,d;return null!==(t=null!==(n=null!==(r=null===(o=e.completedAt)||void 0===o||null===(a=o.toMillis)||void 0===a?void 0:a.call(o))&&void 0!==r?r:null===(i=e.updatedAt)||void 0===i||null===(s=i.toMillis)||void 0===s?void 0:s.call(i))&&void 0!==n?n:null===(l=e.createdAt)||void 0===l||null===(d=l.toMillis)||void 0===d?void 0:d.call(l))&&void 0!==t?t:0};return n(t)-n(e)});if(e.length>0){const t=await(0,Sn.J9)(ar.id,e[0].id);t&&(o=t.fieldValues||{},a=t.signatures||{},i=t.signatureMeta||{})}}catch(r){}let s=null,l=null;try{const n=(0,Pe.getSelectedOrganizationId)()||ue,r=await(0,Pe.getUserOrganizationData)(n||void 0);var e,t;if(r)s=(null===(e=r.settings)||void 0===e||null===(t=e.branding)||void 0===t?void 0:t.logoUrl)||null,l=r.name||null}catch(r){}const d=(await Promise.all([n.e(6396),n.e(6540)]).then(n.bind(n,6540))).generatePdfFromDocument,c=await d({title:ar.title,fileName:ar.fileName,editorHtml:ar.editorHtml,textContent:ar.textContent,fieldValues:o,signatures:a,signatureMeta:i,organizationLogoUrl:s,organizationName:l}),u=c.url,m=c.filename,p=document.createElement("a");p.href=u,p.download=m,document.body.appendChild(p),p.click(),document.body.removeChild(p),setTimeout(()=>{try{URL.revokeObjectURL(u)}catch(e){}},1500)}catch(o){console.error("\u274c PDF export failed:",o),Ie.Ay.error("PDF export failed: ".concat((null===o||void 0===o?void 0:o.message)||"Unknown error"))}finally{qc(!1)}else Ie.Ay.error("No document loaded to export.")},[ar,ue,Pe.getSelectedOrganizationId,Pe.getUserOrganizationData]);(0,i.useEffect)(()=>{if(jc&&Ic.current){const e=Ic.current.getBoundingClientRect();Rc({left:e.left,top:e.bottom+8})}},[jc]),(0,i.useEffect)(()=>{(0,W.gg)("\ud83c\udfa8 Favicon/title effect triggered:",{hasWorkspaceObject:!!xd,workspaceName:null===xd||void 0===xd?void 0:xd.name,emoji:null===xd||void 0===xd?void 0:xd.emoji,docTitle:null===ar||void 0===ar?void 0:ar.title,currentPage:Ve}),console.log("[Favicon]",{emoji:null===xd||void 0===xd?void 0:xd.emoji,name:null===xd||void 0===xd?void 0:xd.name}),null!==xd&&void 0!==xd&&xd.emoji?((0,W.gg)("\ud83c\udfa8 Updating favicon to workspace emoji:",xd.emoji),no(xd.emoji)):xd&&((0,W.gg)("\ud83c\udfa8 No emoji found, restoring default favicon"),to()),null!==ar&&void 0!==ar&&ar.title&&null!==xd&&void 0!==xd&&xd.name?document.title="".concat(ar.title," \u2013 ").concat(xd.name," \u2013 Based"):null!==xd&&void 0!==xd&&xd.name?document.title="".concat(xd.name," \u2013 Based"):document.title="Based \u2013 One Place to Run Your Back Office",(0,W.gg)("\ud83d\udcc4 Updated page title to:",document.title)},[null===xd||void 0===xd?void 0:xd.emoji,null===xd||void 0===xd?void 0:xd.name,xd,null===ar||void 0===ar?void 0:ar.title,Ve]);const Jp=async()=>
1{if(!na)return void console.error("No document data available for deletion");const e=na.doc,t=na.isGlobalView,n=na.currentWorkspace;if(t||null===e||void 0===e||!e.locked){ba(null),ja(!0);try{let a=!1;if(t){const t=(0,ae.Gp)(e,ia,{isGlobalView:!0});await(0,H.Nn)(e.id,t),a=!0}else{const t=await(0,H.vD)(e.id,n);if(null!==t&&void 0!==t&&t.shouldDelete){if((0,oe.z7)(e))return Ie.Ay.error('To permanently delete this secrets document, use All documents and type "'.concat(ae.ZE,'".')),Xo(!1),ra(null),sa(""),void ba(null);await(0,H.Nn)(e.id),a=!0}}if(t){const e=await(0,H.gc)(Fe,Or);Rn(e)}else Rn(t=>(0,o.A)((0,o.A)({},t),{},{documents:((null===t||void 0===t?void 0:t.documents)||[]).filter(t=>t.id!==e.id)}));if(dt.trim())try{const e=await(0,H.mR)(dt,Or);gt(e)}catch(r){console.error("Search refresh after delete:",r),gt([])}Ie.Ay.success(a?"Document deleted successfully":"Document removed from workspace"),Xo(!1),ra(null),sa(""),ba(null)}catch(a){console.error("Error deleting document:",a);const e=(null===a||void 0===a?void 0:a.message)||"Failed to delete document. Please try again.";(0,ae.LD)(e)?ba(e):(Ie.Ay.error(e),Xo(!1),ra(null),sa(""))}finally{ja(!1)}}},qp=async()=>{const e=Array.from(jl);if(0!==e.length){Ba(!0);try{const t=((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).filter(t=>e.includes(t.id)),n=t.filter(e=>!(0,ae.rg)(e)),r=t.filter(e=>(0,ae.rg)(e));for(const e of n)await(0,H.Nn)(e.id);const o=await(0,H.gc)(Fe,Or);Rn(o),Nl(new Set),n.length>0&&Ie.Ay.success(r.length>0?"".concat(n.length," document").concat(1===n.length?"":"s"," deleted. ").concat(r.length," locked or secrets document").concat(1===r.length?"":"s"," skipped."):"".concat(n.length," document").concat(1===n.length?"":"s"," deleted")),0===n.length&&r.length>0&&Ie.Ay.error("All ".concat(r.length," selected document").concat(1===r.length?"":"s"," are locked or secrets and could not be deleted."))}catch(t){console.error("Bulk delete error:",t),Ie.Ay.error((null===t||void 0===t?void 0:t.message)||"Failed to delete some documents")}finally{Ra(!1),Ba(!1)}}},Hp=async()=>{const e=Array.from(jl);if(0===e.length||!Lo)return;Ba(!0);const t=[];try{for(const r of e){const e=await(0,H.vD)(r,Lo);if(null!==e&&void 0!==e&&e.shouldDelete){const e=((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).find(e=>e.id===r);if((0,oe.z7)(e)){t.push(r);continue}await(0,H.Nn)(r)}}const n=new Set(e.filter(e=>!t.includes(e)));Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:((null===e||void 0===e?void 0:e.documents)||[]).filter(e=>!n.has(e.id))})),Nl(new Set),n.size>0&&t.length>0?Ie.Ay.success("".concat(n.size," document").concat(1===n.size?"":"s"," removed. ").concat(t.length," secrets document").concat(1===t.length?"":"s"," kept \u2014 delete from All documents.")):n.size>0?Ie.Ay.success("".concat(n.size," document").concat(1===n.size?"":"s"," removed from workspace")):t.length>0&&Ie.Ay.error('Secrets documents were not deleted. Use All documents and type "'.concat(ae.ZE,'".'))}catch(n){console.error("Bulk remove error:",n),Ie.Ay.error((null===n||void 0===n?void 0:n.message)||"Failed to remove some documents")}finally{_a(!1),Ba(!1)}},Gp=(0,i.useCallback)((e,t)=>{const n=new Set(e),a=t||null;Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:((null===e||void 0===e?void 0:e.documents)||[]).map(e=>{if(!n.has(e.id))return e;if(!a){e.folderId;const t=(0,r.A)(e,Xa);return(0,o.A)((0,o.A)({},t),{},{updatedAt:new Date})}return(0,o.A)((0,o.A)({},e),{},{folderId:a,updatedAt:new Date})})})),ir(e=>{if(!e||!n.has(e.id))return e;if(!a){e.folderId;const t=(0,r.A)(e,ei);return(0,o.A)({},t)}return(0,o.A)((0,o.A)({},e),{},{folderId:a})})},[]),Kp=(0,i.useCallback)(async(e,t)=>{const n=Array.isArray(e)?e.filter(Boolean):[];if(0===n.length)return;const r=new Map;for(const i of n){const e=((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).find(e=>e.id===i);r.set(i,Ft(e))}Gp(n,t),gd(!1),Nl(new Set);try{await Promise.all(n.map(e=>ua(e,t))),Ie.Ay.success(t?"Moved ".concat(n.length," document").concat(1===n.length?"":"s"," to folder"):"Removed ".concat(n.length," document").concat(1===n.length?"":"s"," from folder"))}catch(a){console.error("Move to folder error:",a);for(const e of n){var o;Gp([e],null!==(o=r.get(e))&&void 0!==o?o:null)}Ie.Ay.error((null===a||void 0===a?void 0:a.message)||"Failed to move documents")}},[Gp,null===Pn||void 0===Pn?void 0:Pn.documents]),Qp=(0,i.useCallback)(e=>{const t=Or.find(t=>
1t.id===e);return Ot(null===t||void 0===t?void 0:t.documentFolders)},[Or]),Yp=(0,i.useCallback)(()=>Qp(Lo),[Qp,Lo]),Zp=(0,i.useCallback)(async function(e){const t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:null)||Lo;if(t)try{const n=(await ca(t,Qp(t),e)).folders;Fr(e=>e.map(e=>e.id===t?(0,o.A)((0,o.A)({},e),{},{documentFolders:n}):e)),String(t)!==String(Lo)&&(Ii(!0),hd.current=null,_o(t)),Il(null),Bl(!1),ql(""),Ie.Ay.success("Folder created")}catch(n){throw Ie.Ay.error((null===n||void 0===n?void 0:n.message)||"Failed to create folder"),n}},[Lo,Qp]);(0,i.useEffect)(()=>{var e;zl&&(null===(e=ld.current)||void 0===e||e.focus())},[zl]),(0,i.useEffect)(()=>{var e;nd&&(null===(e=cd.current)||void 0===e||e.focus())},[nd]),(0,i.useEffect)(()=>{Xl(!1),rd(!1),sd("")},[El]),(0,i.useEffect)(()=>{if(!$l)return;const e=e=>{dd.current&&!dd.current.contains(e.target)&&Xl(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[$l]);const $p=(0,i.useCallback)(async(e,t)=>{if(Lo)try{const n=await async function(e,t,n,r){const a=String(r||"").trim();if(!a)throw new Error("Folder name is required");if(!n)throw new Error("folderId is required");const i=Ot(t).map(e=>e.id===n?(0,o.A)((0,o.A)({},e),{},{name:a}):e);if(!i.some(e=>e.id===n))throw new Error("Folder not found");if(i.filter(e=>e.name.toLowerCase()===a.toLowerCase()).length>1)throw new Error("A folder with that name already exists");return await da(e,i),i}(Lo,Yp(),e,t);Fr(e=>e.map(e=>e.id===Lo?(0,o.A)((0,o.A)({},e),{},{documentFolders:n}):e)),Ie.Ay.success("Folder renamed")}catch(n){throw Ie.Ay.error((null===n||void 0===n?void 0:n.message)||"Failed to rename folder"),n}},[Lo,Yp]),Xp=(0,i.useCallback)(e=>{if(!e)return;const t=Yp().find(t=>t.id===e);t&&Rl(t)},[Yp]),eg=(0,i.useCallback)(async e=>{if(!Lo||null===Tl||void 0===Tl||!Tl.id)return;const t=Tl.id,n=((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).filter(e=>Ft(e)===t);_l(!0);try{if("withDocuments"===e){const e=n.filter(e=>!(0,ae.rg)(e)),t=n.filter(e=>(0,ae.rg)(e));for(const n of e)await(0,H.Nn)(n.id);if(t.length>0&&(await ma(t.map(e=>e.id)),Gp(t.map(e=>e.id),null)),e.length>0){const t=new Set(e.map(e=>e.id));Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:((null===e||void 0===e?void 0:e.documents)||[]).filter(e=>!t.has(e.id))})),ar&&t.has(ar.id)&&(ir(null),Je(null))}e.length>0&&t.length>0?Ie.Ay.success("Folder deleted. ".concat(e.length," document").concat(1===e.length?"":"s"," removed; ").concat(t.length," locked or secrets skipped.")):e.length>0?Ie.Ay.success("Folder and ".concat(e.length," document").concat(1===e.length?"":"s"," deleted")):t.length>0?Ie.Ay.success("Folder deleted. ".concat(t.length," locked or secrets document").concat(1===t.length?"":"s"," kept and unfiled.")):Ie.Ay.success("Folder deleted")}else await ma(n.map(e=>e.id)),Gp(n.map(e=>e.id),null),Ie.Ay.success(n.length>0?"Folder deleted. Documents moved to All documents.":"Folder deleted");const r=await async function(e,t,n){if(!n)throw new Error("folderId is required");const r=Ot(t).filter(e=>e.id!==n);return await da(e,r),r}(Lo,Yp(),t);Fr(e=>e.map(e=>e.id===Lo?(0,o.A)((0,o.A)({},e),{},{documentFolders:r}):e)),El===t&&Il(null),Rl(null)}catch(r){console.error("Delete document folder error:",r),Ie.Ay.error((null===r||void 0===r?void 0:r.message)||"Failed to delete folder")}finally{_l(!1)}},[Lo,Tl,null===Pn||void 0===Pn?void 0:Pn.documents,Gp,Yp,El,ar]),tg=async()=>{if(null===na||void 0===na||!na.doc||null!==na&&void 0!==na&&na.isGlobalView||!ue)return;const e=na.doc;ba(null),ja(!0);try{await(0,H.w5)(e.id,ue,ia),Rn(t=>null!==t&&void 0!==t&&t.documents?(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>t.id===e.id?(0,o.A)((0,o.A)({},t),{},{locked:!1}):t)}):t),ra(e=>e?(0,o.A)((0,o.A)({},e),{},{doc:(0,o.A)((0,o.A)({},e.doc),{},{locked:!1})}):e),sa(""),ba(null)}catch(t){const e=(null===t||void 0===t?void 0:t.message)||"Failed to unlock document.";(0,ae.LD)(e)?ba(e):Ie.Ay.error(e)}finally{ja(!1)}},ng=async e=>{try{(0,W.gg)("\ud83d\udccb Duplicating document:",e);const t=(null===Or||void 0===Or?void 0:Or.map(e=>e.id))||[],n=await(0,H.B5)(e,t,{folderId:El||null});return(0,W.gg)("\u2705 Document duplicated:",n.id),Ie.Ay.success("Document duplicated successfully"),await(0,H.gc)(Fe,Or),n}catch(t){throw console.error("\u274c Error duplicating document:",t),Ie.Ay.error("Failed to duplicate document. Please try again."),t}};(0,i.useEffect)(()=>{localStorage.setItem("documentLayout",pn)},[pn]),(0,i.useEffect)(()=>{try{localStorage.setItem("kbViewMode",dn)}catch(e){}},[dn]),(0,i.useEffect)(()=>
1{if(null===Pn||void 0===Pn||!Pn.documents||0===Pn.documents.length)return;let e=null;Lo&&("string"===typeof Lo?e=Lo:"object"===typeof Lo&&null!==Lo&&(e=Lo.id||Lo._id||Lo.workspaceId));const t=e?Pn.documents.filter(t=>!!Array.isArray(t.workspaceIds)&&t.workspaceIds.some(t=>String(t)===String(e))):Pn.documents;if(0===t.length)return;const n=new Set;t.forEach(e=>{const t=e.category||"Uncategorized";n.add(t)});const r=Array.from(n);r.length>0&&Qt(e=>{const t=(0,o.A)({},e);let n=!1;return r.forEach(e=>{void 0===t[e]&&(t[e]=!0,n=!0)}),n?t:e})},[null===Pn||void 0===Pn?void 0:Pn.documents,Lo]);const rg=(0,i.useState)(!1),og=(0,a.A)(rg,2),ag=og[0],ig=og[1],sg=(0,i.useState)(""),lg=(0,a.A)(sg,2),dg=lg[0],cg=lg[1],ug=(0,i.useState)(!1),mg=(0,a.A)(ug,2),pg=mg[0],gg=mg[1],hg=async e=>{if(Lo)try{const t=(0,B.doc)(G.db,"workspaces",Lo);await(0,B.mZ)(t,{emoji:e,updatedAt:(0,B.O5)()}),Fr(t=>t.map(t=>t.id===Lo?(0,o.A)((0,o.A)({},t),{},{emoji:e}):t)),bd(t=>t?(0,o.A)((0,o.A)({},t),{},{emoji:e}):t),window.dispatchEvent(new CustomEvent("workspacePropertyUpdated",{detail:{workspaceId:Lo,updates:{emoji:e}}})),Ie.Ay.success("Emoji updated!")}catch(t){console.error("Error updating workspace emoji:",t),Ie.Ay.error("Failed to update emoji")}},fg=(0,i.useState)(null),yg=(0,a.A)(fg,2),vg=(yg[0],yg[1]),xg=(0,i.useState)(!1),bg=(0,a.A)(xg,2),wg=(bg[0],bg[1]);(0,i.useEffect)(()=>{(async()=>{if(null===Z||void 0===Z||!Z.uid)return yl(null),void wl(null);try{if("global"===zo){const e=await(0,B.getDoc)((0,B.doc)(G.db,"users",Z.uid));if(e.exists()){const t=e.data();t.globalGridDocumentOrder&&Array.isArray(t.globalGridDocumentOrder)?((0,W.gg)("\ud83d\udcda Loaded global grid document order:",t.globalGridDocumentOrder),yl(t.globalGridDocumentOrder)):yl(null),t.globalCategoryOrder&&Array.isArray(t.globalCategoryOrder)?wl(t.globalCategoryOrder):wl(null)}else yl(null),wl(null)}else if(Lo){const e=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",Lo));if(e.exists()){const t=e.data();if(t.gridDocumentOrder&&Array.isArray(t.gridDocumentOrder)?((0,W.gg)("\ud83d\udcda Loaded workspace grid document order:",t.gridDocumentOrder),yl(t.gridDocumentOrder)):yl(null),t.categoryOrder&&Array.isArray(t.categoryOrder)?wl(t.categoryOrder):wl(null),Array.isArray(t.documentFolders)){const e=Ot(t.documentFolders);Fr(t=>t.map(t=>String(t.id)===String(Lo)?(0,o.A)((0,o.A)({},t),{},{documentFolders:e}):t))}}else yl(null),wl(null)}else yl(null),wl(null)}catch(e){const t="permission-denied"===(null===e||void 0===e?void 0:e.code)||(null===e||void 0===e?void 0:e.message)&&e.message.includes("Missing or insufficient permissions");t&&Lo?((0,W.gg)("Grid document order: no access to workspace, clearing stale workspace selection"),_o(null),Ii(!1)):t||console.error("\u274c Error loading grid document order:",e),yl(null),wl(null)}})()},[zo,Lo,null===Z||void 0===Z?void 0:Z.uid]),(0,i.useEffect)(()=>{if(Lo){(0,W.gg)("\ud83d\udd04 Workspace changed, resetting AI chatbot for:",Lo),al(!0),Wd(!1),tl(!1);const e=hd.current;hd.current=null,Il(null!==e&&void 0!==e?e:null),gd(!1)}},[Lo]),(0,i.useEffect)(()=>{if(null===X||void 0===X||!X.uid||Zs.current)return;Zs.current=!0;(0,ge.httpsCallable)((0,ge.getFunctions)(),"deleteEmptyUntitledDocuments")({}).then(e=>{var t;const n=null===e||void 0===e||null===(t=e.data)||void 0===t?void 0:t.deletedIds;null!==n&&void 0!==n&&n.length&&((0,W.gg)("\ud83e\uddf9 Cleaned up stale Untitled Document(s):",n),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:(e.documents||[]).filter(e=>!n.includes(e.id))})))}).catch(e=>{(0,W.gg)("\u26a0\ufe0f deleteEmptyUntitledDocuments failed (non-blocking):",null===e||void 0===e?void 0:e.message)})},[null===X||void 0===X?void 0:X.uid]),(0,i.useEffect)(()=>{(0,W.gg)("\ud83d\udd0d currentPage changed to:",Ve)},[Ve]);const kg=(0,i.useCallback)(async e=>{if(e&&null!==X&&void 0!==X&&X.uid){(0,W.gg)("\ud83d\udcda Fetching documents for workspace:",e),ce(!0);try{const t=(0,B.P)((0,B.rJ)(G.db,"knowledgeBaseDocuments"),(0,B._M)("workspaceIds","array-contains",e)),n=(await(0,B.GG)(t)).docs.map(e=>(0,o.A)({id:e.id},e.data()));Rn(e=>{const t=Object.fromEntries(e.documents.map(e=>[e.id,e])),r=n.map(e=>(0,io.L$)(t[e.id],e));return(0,o.A)((0,o.A)({},e),{},{documents:r,processed:!0})})}catch(t){console.error("\u274c Error fetching workspace documents:",t),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0}))}finally{ce(!1)}}else(0,W.gg)("\u23f8\ufe0f Skipping document fetch - missing workspace or user")},[null===X||void 0===X?void 0:X.uid]);(0,i.useEffect)(()=>
1{if(su.current&&(su.current(),su.current=null),null===X||void 0===X||!X.uid)return(0,W.gg)("\u23f8\ufe0f Skipping document fetch - missing user"),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0})),void ce(!1);const e=!lu.current;e?((0,W.gg)("\u26a1 Setting up real-time document listener for UID:",X.uid),ce(!0),lu.current=!0):(0,W.gg)("\ud83d\udd04 Updating real-time document listener (workspaceList changed)");try{const t=(0,B.P)((0,B.rJ)(G.db,"knowledgeBaseDocuments"),(0,B._M)("userId","==",X.uid),(0,B.My)("updatedAt","desc")),n=[],r=new Map,a=()=>{const t=Array.from(r.values());(0,W.gg)("\ud83d\udcc4 Total documents (user-owned + workspace-accessible): ".concat(t.length)),(0,W.gg)("\ud83d\udcc4 Document IDs:",t.map(e=>({id:e.id,title:e.title||e.fileName,userId:e.userId,workspaceIds:e.workspaceIds})));const n=wo.current;Rn(e=>{const r=Object.fromEntries(e.documents.map(e=>[e.id,e])),a=t.filter(e=>e.userId===X.uid).length;if(!n||0===n.length){var i;if(Lo&&"global"!==zo)return!0===(null===(i=ko.current)||void 0===i?void 0:i.completed)?((0,W.gg)("\u23f3 WorkspaceList empty after fetch completed \u2014 releasing document gate"),(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0,totalDocumentCount:a})):((0,W.gg)("\u23f3 WorkspaceList not loaded yet, but currentWorkspace is set - waiting to filter documents"),(0,W.gg)("\u23f3 Current workspace from localStorage:",Lo,"activeView:",zo),(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!1,totalDocumentCount:a}));(0,W.gg)("\u23f3 WorkspaceList not loaded yet, keeping all documents unfiltered (global view or no workspace)");const n=t.map(e=>(0,io.L$)(r[e.id],e)),s=Array.from(new Map(n.map(e=>[e.id,e])).values());return(0,o.A)((0,o.A)({},e),{},{documents:s,processed:!0,totalDocumentCount:a})}const s=new Set(n.map(e=>String(e.id)));(0,W.gg)("\ud83d\udd0d Accessible workspace IDs:",Array.from(s));const l=Lo?String("string"===typeof Lo?Lo:Lo.id||Lo._id||Lo.workspaceId):null,d=t.filter(e=>{if(l&&"global"!==zo){const t=e.workspaceIds&&Array.isArray(e.workspaceIds)&&e.workspaceIds.length>0&&e.workspaceIds.some(e=>String(e)===l);return t||(0,W.gg)('\u274c Filtered out document "'.concat(e.title||e.fileName,'": Not in current workspace ').concat(l,", workspaceIds="),e.workspaceIds),t}const t=e.userId===X.uid,n=e.workspaceIds&&Array.isArray(e.workspaceIds)&&e.workspaceIds.length>0&&e.workspaceIds.some(e=>s.has(String(e))),r=t||n;return r||(0,W.gg)('\u274c Filtered out document "'.concat(e.title||e.fileName,'": isUserOwned=').concat(t,", isInAccessibleWorkspace=").concat(n,", workspaceIds="),e.workspaceIds),r}),c=d.map(e=>(0,io.L$)(r[e.id],e)),u=Array.from(new Map(c.map(e=>[e.id,e])).values());return(0,W.gg)("\ud83d\udcca Filtered to ".concat(u.length," accessible documents")),(0,o.A)((0,o.A)({},e),{},{documents:u,processed:!0,totalDocumentCount:a})}),hu.current&&!du.current&&((0,W.gg)("[OrgSwitch] Documents processed for new org, dismissing overlay"),gu(null),hu.current=null,fu.current&&(clearTimeout(fu.current),fu.current=null)),e&&ce(!1)},i=(0,B.aQ)(t,e=>{(0,W.gg)("\ud83d\udcc4 Real-time documents update (user-owned)! Count:",e.size);const t=new Set(e.docs.map(e=>e.id));r.forEach((e,n)=>{e.userId!==X.uid||t.has(n)||r.delete(n)}),e.docs.forEach(e=>{var t,n,a,i,s,l;const d=e.data(),c=new Date;r.set(e.id,(0,o.A)((0,o.A)({id:e.id},d),{},{createdAt:(null===(t=d.createdAt)||void 0===t||null===(n=t.toDate)||void 0===n?void 0:n.call(t))||d.createdAt||c,updatedAt:(null===(a=d.updatedAt)||void 0===a||null===(i=a.toDate)||void 0===i?void 0:i.call(a))||d.updatedAt||c,uploadedAt:(null===(s=d.uploadedAt)||void 0===s||null===(l=s.toDate)||void 0===l?void 0:l.call(s))||d.uploadedAt||c}))}),a()},e=>{console.error("\u274c Error in user-owned documents listener:",e),(0,W.gg)("\u274c Error in user-owned documents listener:",e)});if(n.push(i),Or&&Or.length>0){const e=Or.map(e=>String(e.id));(0,W.gg)("\ud83d\udd0d Setting up listeners for documents in accessible workspaces:",e);e.slice(0,10).forEach(e=>{try{const t=(0,B.P)((0,B.rJ)(G.db,"knowledgeBaseDocuments"),(0,B._M)("workspaceIds","array-contains",e),(0,B.My)("updatedAt","desc")),i=(0,B.aQ)(t,t=>{(0,W.gg)("\ud83d\udcc4 Real-time documents update (workspace ".concat(e,")! Count:"),t.size),(0,W.gg)("\ud83d\udcc4 Worksp
1ace ".concat(e," documents:"),t.docs.map(e=>({id:e.id,title:e.data().title||e.data().fileName,userId:e.data().userId,workspaceId:e.data().workspaceId,workspaceIds:e.data().workspaceIds}))),t.docs.forEach(e=>{var t,n,a,i,s,l;const d=e.data(),c=new Date;r.set(e.id,(0,o.A)((0,o.A)({id:e.id},d),{},{createdAt:(null===(t=d.createdAt)||void 0===t||null===(n=t.toDate)||void 0===n?void 0:n.call(t))||d.createdAt||c,updatedAt:(null===(a=d.updatedAt)||void 0===a||null===(i=a.toDate)||void 0===i?void 0:i.call(a))||d.updatedAt||c,uploadedAt:(null===(s=d.uploadedAt)||void 0===s||null===(l=s.toDate)||void 0===l?void 0:l.call(s))||d.uploadedAt||c}))}),a()},t=>{console.error("\u274c Error in workspace ".concat(e," documents listener:"),t),(0,W.gg)("\u274c Error in workspace ".concat(e," documents listener:"),t),(0,W.gg)("\u274c Error code: ".concat(t.code,", message: ").concat(t.message)),"permission-denied"===t.code&&((0,W.gg)("\u26a0\ufe0f Permission denied for workspace ".concat(e,". User might not have access to this workspace.")),(0,W.gg)("\u26a0\ufe0f Check if user ".concat(X.uid," is in workspace ").concat(e," memberRoles"))),"failed-precondition"===t.code&&(0,W.gg)("\u26a0\ufe0f Firestore index required for workspace ".concat(e,". Check Firebase console for index creation link."))});n.push(i)}catch(t){console.error("\u274c Error setting up query for workspace ".concat(e,":"),t),(0,W.gg)("\u274c Error setting up query for workspace ".concat(e,":"),t)}})}else(0,W.gg)("\u26a0\ufe0f No workspaceList available, skipping workspace document listeners");su.current=()=>{n.forEach(e=>e())}}catch(t){console.error("\u274c Error setting up document listener:",t),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0})),ce(!1)}return()=>{su.current&&((0,W.gg)("\ud83e\uddf9 Cleaning up document listener"),su.current(),su.current=null)}},[null===X||void 0===X?void 0:X.uid,jo,Lo,zo]),(0,i.useEffect)(()=>null!==X&&void 0!==X&&X.isAnonymous?((0,W.gg)("\ud83d\udc64 Skipping for anonymous user"),void Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0}))):null!==X&&void 0!==X&&X.uid?void(0,W.gg)("\u2705 User authenticated - real-time listener will handle documents"):((0,W.gg)("\u23f8\ufe0f No user ID, clearing documents"),void Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0}))),[null===X||void 0===X?void 0:X.uid,null===X||void 0===X?void 0:X.isAnonymous]),(0,i.useEffect)(()=>{(async()=>{const e=(0,Pe.getSelectedOrganizationId)()||ye||ue;if(null!==Z&&void 0!==Z&&Z.uid&&e){(0,W.gg)("[OrgSwitch] ensureDefaultWorkspace effectiveOrgId=".concat(e," (selected=").concat((0,Pe.getSelectedOrganizationId)(),", current=").concat(ye,", org=").concat(ue,")"));try{const t=await(0,H.mC)(Z.uid,e),n=t.workspaceId,r=t.shouldRefreshWorkspaceList;n&&(Fi(n),(0,W.gg)("\u2705 Default workspace ID set:",n)),r&&"undefined"!==typeof window&&(window.dispatchEvent(new CustomEvent("workspacesUpdated")),(0,W.gg)("\ud83d\udce1 Dispatched workspacesUpdated event after setting default workspace"))}catch(t){console.error("\u274c Error ensuring default workspace:",t)}}})()},[null===Z||void 0===Z?void 0:Z.uid,ye,ue]),(0,i.useEffect)(()=>{if("undefined"!==typeof window)if(Lo){const e=String("string"===typeof Lo?Lo:Lo.id||Lo._id||Lo.workspaceId||""),t=(0,en.ft)(null===Z||void 0===Z?void 0:Z.uid);if(localStorage.setItem(t,e),null!==Z&&void 0!==Z&&Z.uid&&localStorage.setItem(en.ut,e),null!==Z&&void 0!==Z&&Z.uid&&e){const t=ye||ue||null;(0,tn.yc)(Z.uid,e,t).catch(()=>{})}}else(0,en.NH)(null===Z||void 0===Z?void 0:Z.uid)},[Lo,null===Z||void 0===Z?void 0:Z.uid,ye,ue]),(0,i.useEffect)(()=>{if(null===Z||void 0===Z||!Z.uid||null!=Lo)return;const e=(0,en.ur)(Z.uid);e&&((0,W.gg)("\ud83d\udd27 Restoring last-used workspace after auth:",e),_o(e))},[null===Z||void 0===Z?void 0:Z.uid,Lo]),(0,i.useEffect)(()=>{localStorage.setItem("activeView",zo)},[zo]),(0,i.useEffect)(()=>{if(Or.length>0&&!Lo&&!Ei&&!an&&(null===X||void 0===X||!X.isAnonymous)){if(du.current&&Or===cu.current)return void(0,W.gg)("[OrgSwitch] Auto-select: skipping, workspace list is still from the old org");const e=du.current,t=setTimeout(async()=>{var t,n;e&&((0,W.gg)("[OrgSwitch] Auto-select: new workspace list arrived, clearing orgSwitchInProgress flag"),du.current=!1,cu.current=null);const r=ye||ue||null,o=(0,en.ur)(null===Z||void 0===Z?void 0:Z.uid,r);if(o&&Or.some(e=>String(e.id)===String(o)))return(0,W.gg)("[OrgSwitch] Auto-select: restoring last-used workspace:",o),_o(o),void Bo("workspace");if(null!==Z&&void 0!==Z&&Z.uid){const e=Or.map(e=>
1e.id),t=await(0,tn.kF)(Z.uid,e);if(null!==t&&void 0!==t&&t.workspaceId&&Or.some(e=>String(e.id)===String(t.workspaceId)))return(0,W.gg)("[OrgSwitch] Auto-select: restoring Firestore recency workspace:",t.workspaceId),_o(t.workspaceId),void Bo("workspace")}let a=(null===(t=Or.find(e=>!0===e.isDefault))||void 0===t?void 0:t.id)||(null===(n=Or.find(e=>"Default Workspace"===e.name))||void 0===n?void 0:n.id);var i;!a&&Oi&&(a=null===(i=Or.find(e=>e.id===Oi))||void 0===i?void 0:i.id);a||(a=Or[0].id),(0,W.gg)("[OrgSwitch] Auto-select: picking workspace:",a,"from list of",Or.length),_o(a),Bo("workspace")},150);return()=>clearTimeout(t)}},[Or,Lo,zo,null===X||void 0===X?void 0:X.isAnonymous,Ei,an,Oi,null===Z||void 0===Z?void 0:Z.uid,ye,ue]),(0,i.useEffect)(()=>{if(Or.length>0&&Lo){const e=String("string"===typeof Lo?Lo:Lo.id||Lo._id||Lo.workspaceId);if(!Or.find(t=>String(t.id)===e))return(0,W.gg)("\u26a0\ufe0f Restored workspace from localStorage not found in workspaceList, clearing:",e),_o(null),Ii(!1),void(0,en.NH)(null===Z||void 0===Z?void 0:Z.uid)}},[Or,Lo]),(0,i.useEffect)(()=>{if(Lo&&Or.length>0){const e=String("string"===typeof Lo?Lo:Lo.id),t=Or.find(t=>String(t.id)===e);if(t){const n=xd?String(xd.id):null,r=(null===xd||void 0===xd?void 0:xd.emoji)!==t.emoji,o=(null===xd||void 0===xd?void 0:xd.name)!==t.name;(!xd||n!==e||r||o)&&((0,W.gg)("\ud83d\udd04 Syncing currentWorkspaceObject with currentWorkspace:",t.name,"emoji:",t.emoji),bd(t))}else if(xd){String(xd.id)!==e&&((0,W.gg)("\ud83e\uddf9 Clearing currentWorkspaceObject - workspace not found in list or changed"),bd(null))}}else!Lo&&xd&&((0,W.gg)("\ud83e\uddf9 Clearing currentWorkspaceObject - no workspace selected"),bd(null))},[Lo,Or,xd]);const Ag=(0,i.useMemo)(()=>!("global"===zo||!xd)&&!["admin","editor"].includes(xd.userRole),[zo,xd]);(0,i.useEffect)(()=>{const e=e=>{(0,W.gg)("\ud83d\udd04 Workspaces updated event received:",e.detail),setTimeout(()=>{if(Lo&&Or.length>0){const e=String("string"===typeof Lo?Lo:Lo.id),t=Or.find(t=>String(t.id)===e);t&&((0,W.gg)("\ud83d\udd04 Updating currentWorkspaceObject from workspace update event, emoji:",t.emoji),bd(t))}},100)};return window.addEventListener("workspacesUpdated",e),()=>{window.removeEventListener("workspacesUpdated",e)}},[Lo,Or]);const jg=async e=>{var t;if(null===ar||void 0===ar||!ar.id)return;(0,W.gg)("\ud83d\udd04 handleWorkspaceChange called with:",e),(0,W.gg)("\ud83d\udd0d Current doc workspace:",null===ar||void 0===ar?void 0:ar.workspace),(0,W.gg)("\ud83d\udd0d Current doc workspaceIds:",null===ar||void 0===ar?void 0:ar.workspaceIds),(0,W.gg)("\ud83d\udd0d Current doc userId:",null===ar||void 0===ar?void 0:ar.userId),(0,W.gg)("\ud83d\udd0d Current user uid:",null===(t=G.j2.currentUser)||void 0===t?void 0:t.uid);const n=Array.isArray(e)?e:[e];(0,W.gg)("\ud83d\udcdd Processing workspaces:",n);const r=[],a=[],i=[];for(const b of n){let e;if(e="object"===typeof b&&null!==b&&void 0!==b&&b.name?b.name:"object"===typeof b&&null!==b&&void 0!==b&&b.id?b.id:b,e=String(e).trim(),"Default"===e){a.push("");continue}let t=null===Or||void 0===Or?void 0:Or.find(t=>t.name===e);if(t||(t=null===Or||void 0===Or?void 0:Or.find(t=>{var n;return(null===(n=t.name)||void 0===n?void 0:n.toLowerCase().trim())===e.toLowerCase().trim()})),t||(t=null===Or||void 0===Or?void 0:Or.find(t=>t.id===e)),!t&&("Default Workspace"===e||"default workspace"===e.toLowerCase())){(0,W.gg)('\ud83d\udd0d "Default Workspace" not in list, attempting to fetch...');try{if(null!==Z&&void 0!==Z&&Z.uid&&ue){const e=(await(0,H.mC)(Z.uid,ue)).workspaceId;if(e&&(t=null===Or||void 0===Or?void 0:Or.find(t=>t.id===e),!t)){const n=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",e));if(n.exists()){const r=n.data();t=(0,o.A)({id:e,name:r.name||"Default Workspace",organizationId:r.organizationId},r),(0,W.gg)('\u2705 Fetched "Default Workspace" directly:',t)}}}}catch(h){console.error("\u274c Error fetching Default Workspace:",h)}}t?(r.push(t.id),a.push(t.name),(0,W.gg)("\u2705 Found workspace: ".concat(e," -> ").concat(t.name," (").concat(t.id,")"))):(i.push(e),console.error('\u274c Workspace not found: "'.concat(e,'"')))}i.length>0&&console.error("\u274c Some workspaces not found:",i),0===r.length&&(r.push(null),a.push("Default"),(0,W.gg)("\u26a0\ufe0f No valid workspaces found, defaulting to Default"));const s=Ft(ar),l=!(!s||function(e,t,n){const r="string"===typeof e?e.trim():"";if(!r)return!1;const o=new Set((Array.isArray(t)?t:[]).map(String).filter(e=>e&&"null"!==e&&"undefined"!==e));return 0!==o.size&&(Array.isArray(n)?n:[]).some(e=>!(!e||!o.has(String(e.id)))&&Ot(e.documentFolders).some(e=>e.id===r))}(s,r,Or)),d=(e,t)=>{if((null===e||void 0===e?void 0:e.id)!==ar.id)return e;const n=(0,o.A)((0,o.A)({},e),t);return l&&delete n.folderId,n},c=(null===ar||void 0===ar?void 0:ar.workspaceIds)||[null];if(r.length===c.length&&r.every(e=>c.includes(e)))return void(0,W.gg)("\u2705 Document already has correct workspaces, no update needed");
1(0,W.gg)("\ud83d\udd04 Updating workspaces...",{from:c,to:r,workspaceNames:a});const u=/^new_|^temp_/.test(String(ar.id));let m=!1;if(!u)try{m=(await(0,B.getDoc)((0,B.doc)(G.db,"knowledgeBaseDocuments",ar.id))).exists()}catch(f){m=!1}if(u||!m){const e={workspaceIds:r,workspace:a.find(e=>"Default"!==e&&""!==e)||"Default",workspaceId:(null===r||void 0===r?void 0:r.length)>0?r[0]:null,updatedAt:Date.now()};if(Es.current=r,Rn(t=>(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>d(t,e))})),ir(t=>d(t,e)),"function"===typeof Cs.current){const e=Ie.Ay.loading("Saving document first\u2026");try{const t=await Cs.current();(null!==t&&void 0!==t&&t.id&&!/^new_|^temp_/.test(String(t.id))?t.id:null)?Ie.Ay.success("Document saved with selected workspace",{id:e}):null!==t&&void 0!==t&&t.skipped?Ie.Ay.dismiss(e):Ie.Ay.error("Could not save document with selected workspace",{id:e})}catch(y){console.error("Autosave after workspace selection failed:",y),Ie.Ay.error("Save failed. You can save manually to apply the workspace.",{id:e})}}else(0,Ie.Ay)("Workspace will be applied when you save.");return}try{var p,g;const e={workspaceIds:r,updatedAt:Date.now()};if(null!==(p=G.j2.currentUser)&&void 0!==p&&p.uid)e.userId=G.j2.currentUser.uid;else{if(null===ar||void 0===ar||!ar.userId)return console.error("\u274c Cannot update document: no userId available"),void Ie.Ay.error("Cannot update document: authentication required");e.userId=ar.userId}const t=a.find(e=>"Default"!==e)||"Default";if(e.workspace=t,r&&r.length>0&&r[0]){const t=r[0];e.workspaceId=t,(0,W.gg)("\u2705 Setting workspaceId to first workspace in array:",t)}else{const n=null===Or||void 0===Or?void 0:Or.find(e=>e.name===t);e.workspaceId=n?n.id:null}(0,W.gg)("\ud83d\udcdd Firestore update data:",e),(0,W.gg)("\ud83d\udd0d Document ID:",ar.id),(0,W.gg)("\ud83d\udd0d Current user:",null===(g=G.j2.currentUser)||void 0===g?void 0:g.uid),(0,W.gg)("\ud83d\udd0d Document userId:",null===ar||void 0===ar?void 0:ar.userId);try{const e=await(0,B.getDoc)((0,B.doc)(G.db,"knowledgeBaseDocuments",ar.id));if(!e.exists())return console.error("\u274c Document does not exist:",ar.id),void Ie.Ay.error("Document not found");{const t=e.data();(0,W.gg)("\ud83d\udd0d Existing document data:",{userId:null===t||void 0===t?void 0:t.userId,workspaceId:null===t||void 0===t?void 0:t.workspaceId,workspaceIds:null===t||void 0===t?void 0:t.workspaceIds,hasUserId:"userId"in t})}}catch(v){console.error("\u274c Error checking document:",v)}await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",ar.id),(0,o.A)((0,o.A)({},e),l?{folderId:(0,B.CL)()}:{})),(0,W.gg)("\u2705 Firestore updated successfully"),Rn(t=>(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>d(t,e))})),ir(t=>d(t,e)),(0,W.gg)("\u2705 Document updated with workspaces:",a)}catch(x){console.error("\u274c Failed to update workspaces:",x);const e=(null===x||void 0===x?void 0:x.message)||(null===x||void 0===x?void 0:x.toString())||"Unknown error";Ie.Ay.error("\u274c Failed to update workspaces: ".concat(e))}},Ng=(0,i.useCallback)(async(e,t)=>{if(t&&e)try{(0,W.gg)("\ud83d\udcdd Updating document title only:",{docId:t,newTitle:e});const n=(0,B.doc)(G.db,"knowledgeBaseDocuments",t),r=await(0,B.getDoc)(n);if(r.exists()){const t=r.data();t.userId===(null===Z||void 0===Z?void 0:Z.uid)?(await(0,B.mZ)(n,{title:e,fileName:e,updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Title updated in Firestore")):(0,W.gg)("\u26a0\ufe0f User does not own this document, skipping Firestore update to avoid permissions error")}else(0,W.gg)("\u26a0\ufe0f Document does not exist yet, skipping Firestore update (will be saved on document save)");Rn(n=>(0,o.A)((0,o.A)({},n),{},{documents:n.documents.map(n=>n.id===t?(0,o.A)((0,o.A)({},n),{},{title:e,fileName:e}):n)})),ir(n=>(null===n||void 0===n?void 0:n.id)===t?(0,o.A)((0,o.A)({},n),{},{title:e,fileName:e}):n),vg(null),wg(!1),(0,W.gg)("\u2705 Title updated successfully")}catch(n){(0,W.gg)("\u26a0\ufe0f Error updating title:",n),Rn(n=>(0,o.A)((0,o.A)({},n),{},{documents:n.documents.map(n=>n.id===t?(0,o.A)((0,o.A)({},n),{},{title:e,fileName:e}):n)})),ir(n=>(null===n||void 0===n?void 0:n.id)===t?(0,o.A)((0,o.A)({},n),{}
1,{title:e,fileName:e}):n)}else(0,W.gg)("\u26a0\ufe0f updateDocumentTitleOnly: Missing docId or newTitle")},[Z]),Cg=(0,i.useCallback)(async function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"General";if(!e||!t)return(0,W.gg)("\u26a0\ufe0f updateDocumentCategoryOnly: Missing docId or category"),!1;const r=/^new_|^temp_/.test(e);if(Rn(r=>(0,o.A)((0,o.A)({},r),{},{documents:r.documents.map(r=>r.id===e?(0,o.A)((0,o.A)({},r),{},{category:t,subcategory:n||"General",updatedAt:new Date}):r)})),ir(r=>(null===r||void 0===r?void 0:r.id)===e?(0,o.A)((0,o.A)({},r),{},{category:t,subcategory:n||"General"}):r),r)return(0,W.gg)("\u2705 Document category updated locally (pending save):",t),!0;try{const r=(0,B.doc)(G.db,"knowledgeBaseDocuments",e),o=await(0,B.getDoc)(r);if(!o.exists())return(0,W.gg)("\u26a0\ufe0f Document does not exist yet, skipping Firestore category update"),!1;const a=o.data();return a.userId===(null===Z||void 0===Z?void 0:Z.uid)?a.category===t&&(a.subcategory||"General")===(n||"General")?((0,W.gg)("\u23ed\ufe0f Category unchanged, skipping Firestore write:",t),!1):(await(0,B.mZ)(r,{category:t,subcategory:n||"General",updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Category updated in Firestore:",t),!0):((0,W.gg)("\u26a0\ufe0f User does not own this document, skipping Firestore category update"),!1)}catch(a){return(0,W.gg)("\u26a0\ufe0f Error updating category in Firestore:",a),!1}},[null===Z||void 0===Z?void 0:Z.uid]),Sg=function(e){let t=e.setKnowledgeBase,n=e.setCurrentDoc;const r=(0,i.useState)(new Set),s=(0,a.A)(r,2),l=s[0],d=s[1],c=(0,i.useCallback)((e,r)=>{t(t=>(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>t.id===e?(0,o.A)((0,o.A)({},t),r):t)})),n(t=>(null===t||void 0===t?void 0:t.id)===e?(0,o.A)((0,o.A)({},t),r):t)},[t,n]),u=(0,i.useCallback)(async(e,t)=>{const n=(0,B.doc)(G.db,"knowledgeBaseDocuments",e);await(0,B.mZ)(n,{coverImageUrl:t,coverImageManual:!0,coverImagePosition:(0,B.CL)()}),c(e,{coverImageUrl:t,coverImagePosition:null})},[c]),m=(0,i.useCallback)(async function(e,t){let n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).showToast,r=void 0===n||n;if(!e||!t||"string"!==typeof t)return;const o=t.trim();o&&(await u(e,o),(0,W.gg)("\u2705 Cover image URL set:",{docId:e}),r&&Ie.Ay.success("Cover image updated"))},[u]),p=(0,i.useCallback)(async function(e,t){let n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).showToast,r=void 0!==n&&n;if(!e)return;const o=(0,ao.vK)(t),a=(0,ao.Hj)(o),i=(0,B.doc)(G.db,"knowledgeBaseDocuments",e);await(0,B.mZ)(i,{coverImagePosition:a?(0,B.CL)():o}),c(e,{coverImagePosition:a?null:o}),(0,W.gg)("\u2705 Cover image position saved:",{docId:e,position:o}),r&&Ie.Ay.success("Cover framing saved")},[c]),g=(0,i.useCallback)(async function(e){let t=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).showToast,n=void 0===t||t;if(!e)return;const r=(0,B.doc)(G.db,"knowledgeBaseDocuments",e);await(0,B.mZ)(r,{coverImageUrl:(0,B.CL)(),coverImageManual:(0,B.CL)(),coverImagePosition:(0,B.CL)()}),c(e,{coverImageUrl:null,coverImagePosition:null}),(0,W.gg)("\u2705 Cover image cleared:",{docId:e}),n&&Ie.Ay.success("Cover image removed")},[c]),h=(0,i.useCallback)(async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.page,r=void 0===n?1:n,o=t.perPage,a=void 0===o?15:o;const i=String(e||"").trim();if(!i)return{photos:[],totalResults:0,page:1,perPage:a};const s=(0,ge.getFunctions)(),l=(0,ge.httpsCallable)(s,"searchPexelsPhotos"),d=await l({query:i,page:r,per_page:a}),c=(null===d||void 0===d?void 0:d.data)||{};return{photos:Array.isArray(c.photos)?c.photos:[],totalResults:"number"===typeof c.total_results?c.total_results:null,page:"number"===typeof c.page?c.page:r,perPage:"number"===typeof c.per_page?c.per_page:a}},[]),f=(0,i.useCallback)(async function(e,t,n){var r,o,a,i;let s=(arguments.length>3&&void 0!==arguments[3]?arguments[3]:{}).showToast,l=void 0===s||s;if(!e||!String(t||"").trim())return!1;const d=(0,ge.getFunctions)(),c=(0,ge.httpsCallable)(d,"searchPexelsPhotos"),m=await c({query:String(t).trim(),page:1,per_page:15}),p=null===m||void 0===m||null===(r=m.data)||void 0===r?void 0:r.photos;if(!p||0===p.length)return l&&Ie.Ay.error("No images found for this search."),!1;const g=p.filter(e=>{var t,r,o;const a=(null===(t=e.src)||void 0===t?void 0:t.landscape)||(null===(r=e.src)||void 0===r?void 0:r.medium)||(null===(o=e.src)||void 0===o?void 0:o.original);return a&&a!==n}),h=g.length>
10?g:p,f=h[Math.floor(Math.random()*h.length)],y=(null===(o=f.src)||void 0===o?void 0:o.landscape)||(null===(a=f.src)||void 0===a?void 0:a.medium)||(null===(i=f.src)||void 0===i?void 0:i.original);return!!y&&(await u(e,y),l&&Ie.Ay.success("Cover image updated"),!0)},[u]),y=(0,i.useCallback)(async function(e,t){let n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).showToast,r=void 0===n||n;if(!e)return!1;const o=await(0,B.getDoc)((0,B.doc)(G.db,"knowledgeBaseDocuments",e)),a=(o.exists()?o.data():{}).documentImageUrls||[];if(0===a.length)return r&&Ie.Ay.error("No images in this document to use as cover."),!1;let i=t?a.indexOf(t):-1;i=i<0?0:(i+1)%a.length;const s=a[i];return await u(e,s),r&&Ie.Ay.success("Cover image updated"),!0},[u]),v=(0,i.useCallback)(async function(e,t){let n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).showToast,r=void 0===n||n;if(e&&String(t||"").trim()){d(t=>new Set(t).add(e));try{var o,a,i,s,l;const n=await(0,B.getDoc)((0,B.doc)(G.db,"knowledgeBaseDocuments",e));if(n.exists()&&null!==(o=n.data())&&void 0!==o&&o.coverImageUrl)return void(0,W.gg)("\u23ed\ufe0f Cover image already exists in Firestore, skipping fetch");const d=(n.exists()?n.data():{}).documentImageUrls||[];if(d.length>0){const t=d[0];return(0,W.gg)("\ud83d\uddbc\ufe0f Using first document image as cover:",{docId:e}),await u(e,t),(0,W.gg)("\u2705 Cover image set from document:",t),void(r&&Ie.Ay.success("Cover image added"))}(0,W.gg)("\ud83d\uddbc\ufe0f Fetching Pexels cover image for:",{docId:e,query:t});const c=(0,ge.getFunctions)(),m=(0,ge.httpsCallable)(c,"searchPexelsPhotos"),p=await m({query:String(t).trim(),page:1,per_page:10}),g=null===p||void 0===p||null===(a=p.data)||void 0===a?void 0:a.photos;if(!g||0===g.length)return(0,W.gg)("\u23ed\ufe0f No Pexels results for query:",t),void(r&&Ie.Ay.error("No images found for this search."));const h=g[Math.floor(Math.random()*g.length)],f=(null===(i=h.src)||void 0===i?void 0:i.landscape)||(null===(s=h.src)||void 0===s?void 0:s.medium)||(null===(l=h.src)||void 0===l?void 0:l.original);if(!f)return;await u(e,f),(0,W.gg)("\u2705 Cover image set:",f),r&&Ie.Ay.success("Cover image added")}catch(c){console.warn("\u26a0\ufe0f Failed to fetch Pexels cover image:",null===c||void 0===c?void 0:c.message),r&&Ie.Ay.error("Failed to fetch cover image. Please try again.")}finally{d(t=>{const n=new Set(t);return n.delete(e),n})}}},[u]);return{fetchCoverImage:v,fetchingCoverDocIds:l,setCoverImageUrl:m,setCoverImagePosition:p,clearCoverImage:g,searchPexelsForCover:h,randomPexelsCoverImage:f,cycleDocumentCoverImage:y}}({setKnowledgeBase:Rn,setCurrentDoc:ir}),Eg=Sg.fetchCoverImage,Ig=Sg.fetchingCoverDocIds,Dg=Sg.setCoverImageUrl,Pg=Sg.setCoverImagePosition,Tg=Sg.clearCoverImage,Rg=Sg.searchPexelsForCover,Og=Sg.randomPexelsCoverImage,Fg=Sg.cycleDocumentCoverImage,Lg=(0,i.useRef)(null),_g=(0,i.useRef)(Ve);(0,i.useEffect)(()=>{null!==ar&&void 0!==ar&&ar.id&&Ve&&ar.id===Ve&&(Lg.current=ar)},[ar,Ve]),(0,i.useEffect)(()=>{const e=_g.current;if(_g.current=Ve,e===Ve)return;if(!e||String(e).startsWith("new_"))return;const t=Lg.current;if(!t||t.id!==e)return;if(!(0,co.U)(t))return;const n=(0,co.J$)(t);Eg(e,n,{showToast:!1}).catch(()=>{})},[Ve,Eg]);const Ug=(0,i.useState)(null),Mg=(0,a.A)(Ug,2),zg=Mg[0],Bg=Mg[1],Wg=(0,i.useCallback)((e,t)=>{t&&(t.stopPropagation(),t.preventDefault()),null!==e&&void 0!==e&&e.id&&Bg({id:e.id,title:e.title,fileName:e.fileName})},[]),Vg=(0,i.useState)(new Set),Jg=(0,a.A)(Vg,2),qg=Jg[0],Hg=Jg[1],Gg=(0,i.useCallback)(async e=>{var t;if(null===e||void 0===e||!e.id||qg.has(e.id))return;const n=null!==(t=e.workspaceIds)&&void 0!==t&&t.length?e.workspaceIds:(null===Or||void 0===Or?void 0:Or.map(e=>e.id))||[];Hg(t=>new Set(t).add(e.id));try{const t=await(0,H.YE)(e.id,n),r=(null===t||void 0===t?void 0:t.textContent)||(null===t||void 0===t?void 0:t.title)||"";if(!r||!String(r).trim())return void Ie.Ay.error("No content to generate category from.");const o=await(0,so.V)(String(r).trim());if(null===o||void 0===o||!o.category||(0,co.IE)(o.category))return void Ie.Ay.error("Could not generate category.");await Cg(e.id,o.category,o.subcategory)?Ie.Ay.success("AI updated the category",{id:co.z1}):Ie.Ay.error("Could not save the generated category.")}catch(r){console.warn("Failed to fetch category:",r),Ie.Ay.error("Failed to generate category. Please try again.")}finally{Hg(t=>{const n=new Set(t);return n.delete(e.id),n})}},[Or,Cg]),Kg=(0,i.useRef)(new Set),Qg=(0,i.useRef)(new Set);(0,i.useEffect)(()=>{const e=(null===Pn||void 0===Pn?void 0:Pn.documents)||[];for(const t of e){if(null===t||void 0===t||!t.id||null!==t&&void 0!==t&&t.isNew||"claude"!==(null===t||void 0===t?void 0:t.createdBy))continue;if(Kg.current.has(t.id))continue;const e="image"===t.type||t.fileType&&String(t.fileType).startsWith("image/"),n=(0,co.Q4)(t.title,t.textContent),r=!t.coverImageUrl&&!e&&n.length>=co.cF,a=(0,co.IE)(t.category),i=(t.textContent||t.title||"").replace(/<[^>]*>/g,"").trim();if(!t.isEncrypted&&t.userId===(null===Z||void 0===Z?void 0:Z.uid)&&(t.title||t.textContent)&&!Qg.current.has(t.id)){Qg.current.add(t.id);const e=t.title||"Untitled Document",n=(t.textContent||"").replace(/<[^>]*>/g," ").trim();(async()=>{try{var r,a;const i={editorJson:(0,Wn.p)(e,n||e),editorHtml:"<h1>".concat((e||"").replace(/</g,"&lt;"),"</h1><p>").concat((n||"").replace(/</g,"&lt;").replace(/\n/g,"</p><p>"),"</p>"),title:e,textContent:n||e||"",category:t.category||"",workspace:t.workspace||"Default",workspaceIds:t.workspaceIds||[],createdAtISO:(null===(r=t.createdAt)||void 0===r||null===(a=r.toISO)||void 0===a?void 0:a.call(r))||t.createdAt||(new Date).toISOString(),updatedAtISO:(new Date).toISOString()},s=await Q.E.encryptDocumentContent(i,t.userId,Array.isArray(t.workspaceIds)?t.workspaceIds:t.workspaceId?[t.workspaceId]:[]);await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",t.id),(0,o.A)((0,o.A)({},s),{},{textContent:"[Encrypted Content]",editorJson:(0,B.CL)(),editorHtml:(0,B.CL)(),updatedAt:(0,B.O5)()})),(0,W.gg)("\ud83d\udd12 Auto-encrypted MCP/Claude document:",t.id),Ie.Ay.success("Document encrypted")}catch(i){console.error("Auto-encrypt failed for doc",t.id,i),Qg.current.delete(t.id),Ie.Ay.error("Could not encrypt document. Save manually to encrypt.")}})()}(r||a)&&(Kg.current.add(t.id),r&&Eg(t.id,n).catch(()=>{}),a&&(0,co.Wy)(i)&&(0,so.V)(i).then(e=>null!==e&&void 0!==e&&e.category&&!(0,co.IE)(e.category)?Cg(t.id,e.category,e.subcategory).then(e=>{e&&Ie.Ay.success("AI updated the category",{id:co.z1})}
1):null).catch(()=>{}))}},[null===Pn||void 0===Pn?void 0:Pn.documents,null===Z||void 0===Z?void 0:Z.uid,Eg,Cg]);const Yg=(0,i.useCallback)((e,t)=>{vg(e),wg(t)},[]),Zg=(0,i.useCallback)(async e=>{if(null===Z||void 0===Z||!Z.uid)return console.error("Cannot create workspace: missing currentUser"),Ie.Ay.error("Unable to create workspace. Please refresh the page."),null;const t=(0,Pe.getSelectedOrganizationId)()||ue;if(!t)return console.error("Cannot create workspace: missing organizationId"),Ie.Ay.error("Unable to create workspace. Please select an organization."),null;try{(0,W.gg)("\ud83d\udd12 Checking organization permissions before workspace creation...",{selectedOrgId:t,organizationId:ue});const e=await(0,Pe.getUserOrganizationData)(t);if(!e)return(0,W.gg)("\u274c No organization data found"),Ie.Ay.error("Unable to verify organization permissions. Please refresh the page."),null;if((0,W.gg)("\ud83d\udccb Organization data:",{orgId:e.id,orgName:e.name,userRole:e.role,isEditor:e.isEditor,isAdmin:e.isAdmin}),"viewer"===e.role)return(0,W.gg)("\ud83d\udeab BLOCKED: User is a viewer, cannot create workspaces"),Ie.Ay.error("Your viewer permissions don't allow creation of new workspaces. Only editors and admins can create workspaces."),null;if(!e.isEditor&&!e.isAdmin)return(0,W.gg)("\ud83d\udeab BLOCKED: User is not an editor or admin",{role:e.role,isEditor:e.isEditor,isAdmin:e.isAdmin}),"viewer"===e.role?Ie.Ay.error("Your viewer permissions don't allow creation of new workspaces. Only editors and admins can create workspaces."):Ie.Ay.error("You do not have permission to create workspaces. Only editors and admins can create workspaces."),null;(0,W.gg)("\u2705 Permission check passed - user can create workspaces")}catch(r){return console.error("\u274c Error checking organization permissions:",r),(0,W.gg)("\u274c Error checking organization permissions:",r),Ie.Ay.error("Unable to verify organization permissions. Please refresh the page."),null}let n=0;for(;n<3;)try{(0,W.gg)("\ud83d\udd04 Attempt ".concat(n+1,"/").concat(3," to create workspace: ").concat(e)),await Z.getIdToken(!0),(0,W.gg)("\u2705 Auth token refreshed");const r={name:e,organizationId:t,createdAt:new Date,visibility:"organization",memberRoles:{[Z.uid]:"admin"},usageStats:{documentsCount:0,storageUsed:0},ownerEmail:Z.email};await new Promise(e=>setTimeout(e,500));const o=await(0,B.gS)((0,B.rJ)(G.db,"workspaces"),r);(0,W.gg)("\u2705 Workspace created successfully:",o.id);const a={id:o.id,name:e,organizationId:t,createdAt:r.createdAt,visibility:r.visibility,memberRoles:r.memberRoles,usageStats:r.usageStats,ownerEmail:r.ownerEmail,userRole:"admin",documentsCount:0,storageUsed:0,description:"",emoji:null};return(0,W.gg)("\ud83d\udd0d Adding workspace to local state:",{workspaceOrgId:a.organizationId,selectedOrgId:t,organizationId:ue,match:a.organizationId===t}),a.organizationId===t||a.organizationId===ue?Fr(e=>{if(e.some(e=>e.id===a.id))return(0,W.gg)("\u26a0\ufe0f Workspace already in list, updating instead of adding"),e.map(e=>e.id===a.id?a:e);const t=[a,...e];return(0,W.gg)("\u2705 Updated workspace list with new workspace:",t.length,"workspaces"),t}):((0,W.gg)("\u26a0\ufe0f Organization ID mismatch - workspace orgId:",a.organizationId,"vs current orgId:",ue),Fr(e=>{if(!e.some(e=>e.id===a.id)){const t=[a,...e];return(0,W.gg)("\u2705 Added workspace despite org mismatch (workspace was just created):",t.length,"workspaces"),t}return e})),window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!0,skipFetch:!1}})),(0,W.gg)("\ud83d\udce2 Dispatched workspacesUpdated event to refresh sidebar"),Ie.Ay.success('Workspace "'.concat(e,'" created successfully!')),a}catch(o){const e=n+1;if(console.error("\u274c Creation attempt ".concat(e," failed:"),o),e>=3)return console.error("\u274c All creation attempts failed"),Ie.Ay.error("Failed to create workspace after multiple attempts. Please try again."),null;n=e,await new Promise(t=>setTimeout(t,1e3*e))}return null},[ue,Z,Pe.getSelectedOrganizationId,Pe.getUserOrganizationData]),$g=ye||ue||(0,Pe.getSelectedOrganizationId)()||null,Xg=Wt(Or,$g),eh=Vt(Xg),th=(e=>{const t=Array.isArray(e)?e.filter(Boolean).map(String):[],n=Jr(t),r=(0,i.useState)(()=>Ut(Lr,t)),o=(0,a.A)(r,2),s=o[0],l=o[1];return(0,i.useEffect)(()=>{const e=++Mr;return zr.set(e,{ids:t,onChange:l}),Kr(),l(e=>{const n=Ut(Lr,t);return _t(e,n)?e:n}),()=>{zr.delete(e),Kr()}},[n]),s})(Xg),nh=Jt(Xg),rh=(0,i.useMemo)(()=>Bt(null===Or||void 0===Or?void 0:Or.find(e=>String(e.id)===String(Lo)),Lo,eh,th,nh,$g),[Lo,Or,eh,th,nh,$g]),oh=async e=>{const t=sr.current;if((0,W.gg)("\ud83d\udd04 Category change requested:",{from:null===t||void 0===t?void 0:t.category,to:e,docId:null===t||void 0===t?void 0:t.id}),null===t||void 0===t||!t.id)return;const n=/^new_|^temp_/.test(t.id);if(Rn(n=>(0,o.A)((0,o.A)({},n),{},{documents:n.documents.map(n=>n.id===t.id?(0,o.A)((0,o.A)({},n),{},{category:e,updatedAt:new Date}):n)})),ir(n=>n&&n.id===t.id?(0,o.A)((0,o.A)({},n),{},{category:e,updatedAt:new Date}):n),n)return(0,W.gg)("\u2705 Document category updated locally (pending save): ".concat(e)),void(0,Ie.Ay)("Save the document to sync your category.",{duration:4500});try{await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",t.id),{category:e,updatedAt:(0,B.O5)()}),(0,W.gg)("\u2705 Document category updated in Firestore: ".concat(e))}catch(r){console.error("\u274c Failed to update category:",r),Ie.Ay.error("Failed to update category. Please try again.")}};async function ah(e,t,n,a){let i=arguments.length>4&&void 0!==arguments[4]&&arguments[4],s=arguments.length>5&&void 0!==arguments[5]&&arguments[5];
1if((0,W.gg)("\ud83d\udd0d PERSIST EDITOR INPUTS:",{dataToSave:e,html:t,title:n,isUpdate:a,isManualSave:i,skipValidation:s,"dataToSave.isEncrypted":null===e||void 0===e?void 0:e.isEncrypted}),null===ar||void 0===ar||!ar.id)return;const l=Gs.current,d=null===l||void 0===l?void 0:l.documentId;if(l&&d&&null!==Z&&void 0!==Z&&Z.uid&&"pdf"===(null===ar||void 0===ar?void 0:ar.viewerMode)&&String(ar.id)===String(d)&&!/^new_|^temp_/.test(String(ar.id)))try{const e=await ya(Z.uid,l.storagePath,d,l.fileName||"document.pdf"),t=e.url,n=e.previewUrl;await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",d),{url:t,previewUrl:n,updatedAt:(0,B.O5)()}),Gs.current=null,ir(e=>(null===e||void 0===e?void 0:e.id)===d?(0,o.A)((0,o.A)({},e),{},{url:t,previewUrl:n}):e),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===d?(0,o.A)((0,o.A)({},e),{},{url:t,previewUrl:n}):e)})),Ie.Ay.success("PDF moved to permanent storage.")}catch(D){console.error("PDF viewer doc \u2014 canonical Storage copy retry failed:",D),"storage/object-not-found"===(null===D||void 0===D?void 0:D.code)?(Gs.current=null,Ie.Ay.error("The temporary PDF file is no longer available. Re-upload the PDF to restore this document.",{duration:8e3})):i&&Ie.Ay.error("Still could not move your PDF to permanent storage. Check your connection and save again.",{duration:6500})}if(!s)try{const r=ne.validateBeforeSave(e);if(r.willBeModified)return Bs({dataToSave:e,html:t,title:n,isUpdate:a,isManualSave:i}),qs(r),_s(!0),void Un(null)}catch(P){console.warn("\u26a0\ufe0f Pre-save validation error:",P)}const c=String(ar.id);ie.markSaving(c),Un("Saving...");const u=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.find(e=>void 0!==e&&null!==e)},m=async e=>{if(Array.isArray(e)&&e.length>0)return e;if(null!==ar&&void 0!==ar&&ar.isNew){const e=Oi||(await(0,H.mC)(null===Z||void 0===Z?void 0:Z.uid,ue)).workspaceId;return e?[e]:[]}const t=[];if(Lo&&"Default"!==Lo&&"default"!==Lo){let e;if("string"===typeof Lo?e=Lo:"object"===typeof Lo&&(e=Lo.id||Lo._id||Lo.workspaceId),e&&"Default"!==e&&"default"!==e)t.push(e);else{const e=Oi||(await(0,H.mC)(null===Z||void 0===Z?void 0:Z.uid,ue)).workspaceId;e&&t.push(e)}}else{const e=Oi||(await(0,H.mC)(null===Z||void 0===Z?void 0:Z.uid,ue)).workspaceId;e&&t.push(e)}return t};try{var p,g,h,f;const l=e=>{null!=e&&"undefined"!==typeof window&&window.dispatchEvent(new CustomEvent(ee.Xy,{detail:{documentId:String(e)}}))},d=String(ar.id||""),A=/^new_|^temp_/.test(d),j=Boolean(a&&!A);(0,W.gg)("\ud83d\udcbe persistEditor operation:",{isUpdate:a,shouldUpdate:j,docId:ar.id,isNew:ar.isNew,title:n,isTempId:A,currentWorkspace:Lo,currentDocCategory:null===ar||void 0===ar?void 0:ar.category,dataToSaveCategory:null===e||void 0===e?void 0:e.category});const N=e||{},C=(N._editorJsonForPreservation,N._editorHtmlForPreservation,N.aiGeneratedToolbarUntil,N.lastAIGenerateOptions,N.showAIRevisionBar,N._pdfCanonicalCopy),S=N._pdfIndexPlaintext,E=(0,r.A)(N,ti);if(!j){var y,v,x,b;if(!("pdf"===(null===E||void 0===E?void 0:E.viewerMode)&&((null===E||void 0===E?void 0:E.url)||(null===E||void 0===E?void 0:E.previewUrl))&&"string"===typeof(null===E||void 0===E?void 0:E.textContent)&&E.textContent.trim().length>0)){const e=!n||"string"===typeof n&&"Untitled Document"===n.trim(),r=(e=>(e||"").replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim())(t);if(e&&(!r||"Untitled Document"===r))return(0,W.gg)("\u26a0\ufe0f Skipping create: document has no title or content"),Un(null),(0,Ie.Ay)("Add a title or content to save",{icon:"\ud83d\udcdd"}),{skipped:!0,reason:"empty"}}if(Hs.current.has(ar.id))return(0,W.gg)("\u26a0\ufe0f Document creation already in progress for:",ar.id,"- skipping duplicate create"),Un("Saved"),void setTimeout(()=>Un(null),500);const r=null===Pn||void 0===Pn||null===(y=Pn.documents)||void 0===y?void 0:y.find(e=>{if(!("Untitled"===n||"Untitled Document"===n||"Untitled"===(null===ar||void 0===ar?void 0:ar.title)||"Untitled Document"===(null===ar||void 0===ar?void 0:ar.title)))return!1;if(!(e.id&&!/^new_|^temp_/.test(e.id)))return!1;if(!("Untitled"===e.title||"Untitled Document"===e.title||e.title===n||e.title===(null===ar||void 0===ar?void 0:ar.title)))return!1;if(!(e.userId===(null===Z||void 0===Z?void 0:Z.uid)))return!1;const t=e.createdAt||e.updatedAt;if(!t)return!1;{let e;e=t.toMillis?t.toMillis():t instanceof Date?t.getTime():"string"===typeof t?new Date(t).getTime():t.seconds?1e3*t.seconds+(t.nanoseconds||0)/1e6:new Date(t).getTime();const n=Date.now()-e;if(n>5e3||n<0)return!1}return(0,W.gg)("\ud83d\udd0d Found existing document that may have been created from this temp ID:",{docId:e.id,docTitle:e.title,createdAt:e.createdAt,updatedAt:e.updatedAt,ageMs:t?Date.now()-(t.toMillis?t.toMillis():new Date(t).getTime()):"unknown"}),!0});if(r){(0,W.gg)('\u26a0\ufe0f Document with same title "Untitled" already exists, updating instead of creating:',r.id),(0,se.FP)(ar.id,r.id),ir(e=>(0,o.A)((0,o.A)({},e),{},{id:r.id,isNew:!1})),Je(r.id);const e=(0,B.doc)(G.db,"knowledgeBaseDocuments",r.id);if((await(0,B.getDoc)(e)).exists()){let a;(0,W.gg)("\u2705 Found existing document, updating instead of creating"),a=E&&"object"===typeof E&&E.isEncrypted?(0,o.A)((0,o.A)({},E),{},{title:n||r.title,updatedAt:(0,B.O5)()}):{editorJson:(null===E||void 0===E?void 0:E.editorJson)||E,editorHtml:t,title:n||r.title,fileName:n||r.fileName,textContent:(t||"").replace(/<[^>]*>/g,""),updatedAt:(0,B.O5)()},await(0,B.mZ)(e,a);const i=(0,o.A)((0,o.A)({},r),a);return Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===r.id?i:e)})),ir(i),Je(r.id),ie.markSaved(r.id),Un("Saved"),setTimeout(()=>Un(null),500),l(r.id),i}}ie.markCreating(ar.id),Hs.current.add(ar.id),(0,W.gg)("\ud83d\udd12 Locked document creation for temp ID:",ar.id);const a=await $h(),d=u(lr.current,null===e||void 0===e?void 0:e.category,null===ar||void 0===ar?void 0:ar.category,null===a||void 0===a?void 0:a.category);let c=(null===e||void 0===e?void 0:e.workspaceIds)||(null===ar||void 0===ar?void 0:ar.workspaceIds)||(null===a||void 0===a?void 0:a.workspaceIds);null!==(v=Es.current)&&void 0!==v&&v.length&&(c=Es.current,Es.current=null,(0,W.gg)("\u2705 Create: using workspace IDs from pending selection (autosave after workspace pick)"));const p=A||(null===ar||void 0===ar?void 0:ar.isNew);(0,W.gg)("\ud83d\udd0d Getting default workspace for new document:",{userId:null===Z||void 0===Z?void 0:Z.uid,organizationId:ue,hasOrganizationId:!!ue,currentWorkspaceObject:null===xd||void 0===xd?void 0:xd.organizationId,workspaceListLength:null===Or||void 0===Or?void 0:Or.length});let g,h=null,f=ue;if(f||(null!==xd&&void 0!==xd&&xd.organizationId?(f=xd.organizationId,(0,W.gg)("   - \u2705 Got organizationId from currentWorkspaceObject:",f)):(null===Or||void 0===Or?void 0:Or.length)>0?(f=Or[0].organizationId,(0,W.gg)("   - \u2705 Got organizationId from workspaceList:",f)):Lo&&"object"===typeof Lo&&Lo.organizationId&&(f=Lo.organizationId,(0,W.gg)("   - \u2705 Got organizationId from currentWorkspace object:",f))),(null===Or||void 0===Or?void 0:Or.length)>0){const e=Or.find(e=>"Default Workspace"===e.name);e&&(h=e.id,(0,W.gg)('   - \u2705 Found "Default Workspace" in workspaceList (early check):',h))}if(null!==Z&&void 0!==Z&&Z.uid&&f||((0,W.gg)("   - \u274c ERROR: Cannot get default workspace - missing userId or organizationId"),(0,W.gg)("   - userId:",null===Z||void 0===Z?void 0:Z.uid),(0,W.gg)("   - organizationId:",f),h?(0,W.gg)('   - \u2705 Using "My Workspace" found in workspaceList'):(!f&&(null===Or||void 0===Or?void 0:Or.length)>0&&(f=Or[0].organizationId,(0,W.gg)("   - \ud83d\udd04 Retrying with organizationId from workspaceList:",f)),f||((0,W.gg)('   - \u274c CRITICAL: Cannot create "My Workspace" without organizationId'),(0,W.gg)("   - \u26a0\ufe0f Document will be created without workspace assignment")))),null!==Z&&void 0!==Z&&Z.uid&&f&&!h){let e=0;const t=3;for(;!h&&e<t;){e++,(0,W.gg)("\ud83d\udd04 Attempt ".concat(e,' to get "Default Workspace" as default'));const n=(await(0,H.mC)(Z.uid,f)).workspaceId;if(n)try{const r=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",n));if(r.exists()){const o=r.data();if((0,W.gg)("   - Workspace name (attempt ".concat(e,"):"),o.name),(0,W.gg)("   - Workspace ID:",
1n),"Default Workspace"===o.name){h=n,(0,W.gg)('   - \u2705 SUCCESS: Found "Default Workspace" as default');break}(0,W.gg)("   - \u26a0\ufe0f Attempt ".concat(e,' failed: workspace is "').concat(o.name,'", not "Default Workspace"')),(0,W.gg)("   - \u26a0\ufe0f This workspace (".concat(o.name,") should NOT be used as default")),e<t&&(await new Promise(e=>setTimeout(e,1e3)),(0,W.gg)("   - \ud83d\udd04 Waiting before retry (attempt ".concat(e+1,")...")))}}catch(P){console.error("\u274c Error verifying workspace name (attempt ".concat(e,"):"),P)}else(0,W.gg)("   - \u26a0\ufe0f Attempt ".concat(e,": getOrCreateDefaultWorkspace returned null"))}if(!h&&((0,W.gg)('   - \u274c ERROR: Could not get "Default Workspace" after',t,"attempts"),(null===Or||void 0===Or?void 0:Or.length)>0)){const e=Or.find(e=>"Default Workspace"===e.name);if(e)h=e.id,(0,W.gg)('   - \u2705 Found "Default Workspace" in workspaceList:',h);else{if((0,W.gg)('   - \u26a0\ufe0f "Default Workspace" not found in workspaceList'),f){(0,W.gg)('   - \ud83d\udd04 Last attempt: creating "Default Workspace" with organizationId from workspaceList');const e=(await(0,H.mC)(Z.uid,f)).workspaceId;if(e){const t=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",e));t.exists()&&"Default Workspace"===t.data().name&&(h=e,(0,W.gg)('   - \u2705 Successfully created "Default Workspace" on last attempt:',e))}}h||(0,W.gg)('   - \u274c CRITICAL: Could not get "Default Workspace" - document may be created without workspace')}}}if(h&&h!==Oi){Fi(h);(null===Or||void 0===Or?void 0:Or.some(e=>e.id===h))||"undefined"===typeof window?(0,W.gg)("\u23ed\ufe0f Skipping workspace refresh - Default Workspace already exists"):(window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!1,skipFetch:!1}})),(0,W.gg)("\ud83d\udce1 Dispatched workspacesUpdated event to refresh workspace list (new workspace)"))}if(!p||c&&0!==c.length)g=await m(c);else{let e=!1,t=null;if(Lo&&"Default"!==Lo&&"default"!==Lo&&("string"===typeof Lo?t=Lo:"object"===typeof Lo&&null!==Lo&&(t=Lo.id||Lo._id||Lo.workspaceId),t&&"Default"!==t&&"default"!==t)){const n=xd||(null===Or||void 0===Or?void 0:Or.find(e=>e.id===t));n&&"Default Workspace"!==n.name&&(e=!0,(0,W.gg)("\ud83c\udd95 New document: using current workspace (not Default Workspace):",t,n.name))}e&&t?(g=[t],(0,W.gg)("   - Using current workspace ID:",t)):((0,W.gg)("\ud83c\udd95 New document with no workspace selected, using default workspace"),(0,W.gg)("   - currentWorkspace:",Lo),h?(g=[h],(0,W.gg)("   - Using verified default workspace ID:",h)):((0,W.gg)("   - \u26a0\ufe0f No default workspace found, will use fallback"),g=[]))}if(!g||0===g.length)if((0,W.gg)("\u26a0\ufe0f No workspaceIds found, assigning to default workspace"),h)g=[h],(0,W.gg)("   - Using verified default workspace:",h);else if(f&&null!==Z&&void 0!==Z&&Z.uid){(0,W.gg)('   - \ud83d\udd04 Last attempt: trying to get/create "Default Workspace"');try{const e=(await(0,H.mC)(Z.uid,f)).workspaceId;if(e){const t=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",e));t.exists()&&"Default Workspace"===t.data().name?(g=[e],(0,W.gg)('   - \u2705 Successfully got "Default Workspace" on last attempt:',e)):((0,W.gg)('   - \u274c Last attempt returned non-"Default Workspace" workspace'),g=[])}else(0,W.gg)("   - \u274c Last attempt returned null"),g=[]}catch(P){console.error("\u274c Error in last attempt to get default workspace:",P),g=[]}}else(0,W.gg)('   - \u274c Cannot create "Default Workspace" - missing organizationId or userId'),(0,W.gg)('   - \u26a0\ufe0f Document will be created without workspace assignment (NOT using "Homepath")'),g=[];const k=p?h||null:Lo||null;(0,W.gg)("\u2705 Creating document with workspaceIds:",g),(0,W.gg)("   - isNew:",null===ar||void 0===ar?void 0:ar.isNew),(0,W.gg)("   - existingWorkspaceIds:",c),(0,W.gg)("   - currentWorkspace:",Lo),(0,W.gg)("   - defaultWorkspaceId (state):",Oi),(0,W.gg)("   - verifiedDefaultWorkspaceId:",h),(0,W.gg)("   - finalWorkspaceId (legacy field):",k);const j=null===Or||void 0===Or?void 0:Or.some(e=>e.id===h);if(h&&!j&&"undefined"!==typeof window?setTimeout(()=>{window.dispatchEvent(new CustomEvent("workspacesUpdated",{detail:{needsFullRefresh:!1,skipFetch:!1}})),(0,W.gg)("\ud83d\udce1 Dispatched workspacesUpdated event after creating new Default Workspace")},1e3):(0,W.gg)("\u23ed\ufe0f Skipping workspace refresh - Default Workspace already exists in list"),(null===(x=g)||void 0===x?void 0:x.length)>0&&(null===Or||void 0===Or?void 0:Or.length)>0){const e=g.map(e=>{const t=Or.find(t=>
1t.id===e);return t?t.name:e});(0,W.gg)("   - Workspace names:",e)}let N;try{var w;N=await ne.saveDocument(ar.id,(0,o.A)((0,o.A)({},E),{},{title:(null===E||void 0===E?void 0:E.title)||n,category:d,workspace:(null===E||void 0===E?void 0:E.workspace)||(null===ar||void 0===ar?void 0:ar.workspace)||"Default"}),{html:t,title:n,isUpdate:!1,userId:null===Z||void 0===Z?void 0:Z.uid,workspaceIds:g,currentDoc:ar,originalDoc:null,getWorkspaceIds:m,getOrCreateDefaultWorkspace:H.mC,defaultWorkspaceId:h,organizationId:f,isManualSave:i,skipValidation:s,versionControlEnabled:Yi}),null!==(w=N)&&void 0!==w&&w._contentModified&&Ie.Ay.warning(N._modificationWarning||"Document structure was automatically adjusted during save. Some formatting may have been simplified.")}catch(P){if("ValidationWarning"===P.name)return Bs({dataToSave:e,html:t,title:n,isUpdate:!1,isManualSave:i}),qs(P.validation||{warning:P.message}),_s(!0),void Un(null);throw P}if(C&&"string"===typeof C.storagePath&&C.storagePath&&null!==Z&&void 0!==Z&&Z.uid&&null!==(b=N)&&void 0!==b&&b.id)try{const e=await ya(Z.uid,C.storagePath,N.id,C.fileName||n||"document.pdf"),t=e.url,r=e.previewUrl;await(0,B.mZ)((0,B.doc)(G.db,"knowledgeBaseDocuments",N.id),{url:t,previewUrl:r,updatedAt:(0,B.O5)()}),N=(0,o.A)((0,o.A)({},N),{},{url:t,previewUrl:r}),Gs.current=null}catch(T){console.error("PDF viewer doc \u2014 canonical Storage copy failed:",T);const e="storage/object-not-found"===(null===T||void 0===T?void 0:T.code);e||(Gs.current={documentId:N.id,storagePath:C.storagePath,fileName:C.fileName||n||"document.pdf"}),Ie.Ay.error(e?"The PDF could not be found in temporary storage. Try creating the document again or re-upload the file.":"Could not move your PDF to permanent storage after several tries. It may still open for now, but can break if the temporary file is removed. Save again to retry, or re-upload the PDF if this keeps happening.",{duration:9e3})}const I=(0,o.A)((0,o.A)({},N),{},{isNew:!1});(0,se.FP)(ar.id,I.id),Rn(e=>{const t=[...e.documents.filter(e=>e.id!==ar.id&&e.id!==I.id),I],n=Array.from(new Map(t.map(e=>[e.id,e])).values());return(0,o.A)((0,o.A)({},e),{},{documents:n})});const D=(null===e||void 0===e?void 0:e._editorJsonForPreservation)||(null===e||void 0===e?void 0:e.editorJson)||(null===ar||void 0===ar?void 0:ar.editorJson)||I.editorJson,R=(null===e||void 0===e?void 0:e._editorHtmlForPreservation)||t||(null===ar||void 0===ar?void 0:ar.editorHtml)||I.editorHtml;ir(e=>{if((null===e||void 0===e?void 0:e.id)===ar.id){const a=(0,o.A)((0,o.A)((0,o.A)({},e),I),{},{editorJson:D,editorHtml:R});var t,n,r;if("pdf"===e.viewerMode||"pdf"===I.viewerMode)a.viewerMode="pdf",a.url=null!==(t=I.url)&&void 0!==t?t:e.url,a.previewUrl=null!==(n=I.previewUrl)&&void 0!==n?n:e.previewUrl,a.fileName=null!==(r=I.fileName)&&void 0!==r?r:e.fileName,a.fileType=I.fileType||e.fileType||"application/pdf";return a}return e}),ie.markJustCreated(I.id),ar.id&&ar.id.startsWith("new_")?(Ks.current.set(I.id,ar.id),Qs.current||(Qs.current=ar.id)):Qs.current=I.id,ie.markSaved(I.id);const O="image"===I.type||I.fileType&&I.fileType.startsWith("image/"),F="pdf"===I.viewerMode,L=(0,co.Q4)(n,t);!O&&!F&&!I.coverImageUrl&&L.length>=co.cF&&Eg(I.id,L).catch(()=>{});if((0,co.IE)(I.category)){const e=("pdf"===E.viewerMode&&"string"===typeof S&&S.trim()?S.trim():(t||"").replace(/<[^>]*>/g,"").trim())||n||"";(0,co.Wy)(e)&&(0,so.V)(e).then(e=>{if(null!==e&&void 0!==e&&e.category&&!(0,co.IE)(e.category))return Cg(I.id,e.category,e.subcategory).then(e=>{e&&Ie.Ay.success("AI updated the category",{id:co.z1})});(0,W.gg)("\u23ed\ufe0f [autoCategory] Skipping category write for new doc \u2014 no usable classification")}).catch(()=>{})}const _=ar.id;requestAnimationFrame(()=>{const e=qe.current;e===_||e===I.id?Je(I.id):(0,W.gg)("\u23ed\ufe0f Skipping post-create setCurrentPage \u2014 user left the document",{cp:e,tempIdAtCreate:_,newDocWithId:I.id})}),setTimeout(()=>{Hs.current.delete(ar.id),ie.clearCreating(ar.id),(0,W.gg)("\ud83d\udd13 Unlocked document creation for temp ID:",ar.id,"- document created with ID:",I.id)},1e3),(0,W.gg)("\u2705 Document created successfully with workspaceIds:",g);
1{const e="string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null;if(e&&Array.isArray(I.workspaceIds)&&I.workspaceIds.some(t=>String(t)===String(e)))if(I.isEncrypted&&"pdf"===I.viewerMode&&"string"===typeof S&&S.trim()){const t=(0,o.A)((0,o.A)({},I),{},{textContent:S.trim()});xi(e,bi(Bp,t,ar.id)).catch(e=>console.error("Post-save RAG index:",e))}else if(I.isEncrypted)xi(e,[],{fromEncryptedPostSave:!0}).catch(e=>console.error("Post-save RAG index:",e));else{const n=(t||"").replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim(),r=(0,o.A)((0,o.A)({},I),{},{textContent:"pdf"===I.viewerMode&&"string"===typeof S&&S.trim()?S.trim():n||I.textContent});xi(e,bi(Bp,r,ar.id)).catch(e=>console.error("Post-save RAG index:",e))}}return Un("Saved"),setTimeout(()=>Un(null),900),l(I.id),I}const I=null===Pn||void 0===Pn||null===(p=Pn.documents)||void 0===p?void 0:p.find(e=>e.id===ar.id);(0,W.gg)("\ud83d\udd0d UPDATE: Category sources:",{originalDocCategory:null===I||void 0===I?void 0:I.category,currentDocCategory:null===ar||void 0===ar?void 0:ar.category,dataToSaveCategory:null===e||void 0===e?void 0:e.category,willUse:u(null===I||void 0===I?void 0:I.category,null===ar||void 0===ar?void 0:ar.category,null===e||void 0===e?void 0:e.category)});const D=u(null===I||void 0===I?void 0:I.category,null===ar||void 0===ar?void 0:ar.category,null===e||void 0===e?void 0:e.category);let F,L,_=(null===e||void 0===e?void 0:e.workspaceIds)||(null===ar||void 0===ar?void 0:ar.workspaceIds)||(null===I||void 0===I?void 0:I.workspaceIds);if(null!==(g=Es.current)&&void 0!==g&&g.length&&(_=Es.current,Es.current=null,(0,W.gg)("\u2705 Update: using workspace IDs from pending selection (autosave after workspace pick)")),_&&0!==_.length)F=_,(0,W.gg)("\u2705 UPDATE: Preserving existing workspaceIds:",F);else{(0,W.gg)("\u26a0\ufe0f UPDATE: Document has empty workspaceIds, using default workspace (not currentWorkspace)");const e=Oi||(await(0,H.mC)(null===Z||void 0===Z?void 0:Z.uid,ue)).workspaceId;e?(F=[e],(0,W.gg)("   - Using default workspace ID:",e)):F=await m([])}(0,W.gg)("\u2705 Updating document with workspaceIds:",F);try{var k;L=await ne.saveDocument(ar.id,(0,o.A)((0,o.A)({},E),{},{title:n,category:D}),{html:t,title:n,isUpdate:!0,userId:null===Z||void 0===Z?void 0:Z.uid,workspaceIds:F,currentDoc:ar,originalDoc:I,getWorkspaceIds:m,getOrCreateDefaultWorkspace:H.mC,defaultWorkspaceId:Oi,organizationId:ue,isManualSave:i,skipValidation:s,versionControlEnabled:Yi}),null!==(k=L)&&void 0!==k&&k._contentModified&&Ie.Ay.warning(L._modificationWarning||"Document structure was automatically adjusted during save. Some formatting may have been simplified.")}catch(P){if("ValidationWarning"===P.name)return Bs({dataToSave:e,html:t,title:n,isUpdate:!0,isManualSave:i}),qs(P.validation||{warning:P.message}),_s(!0),void Un(null);throw P}let U=(0,o.A)((0,o.A)({},L),{},{title:n||(null===(h=L)||void 0===h?void 0:h.title)||(null===ar||void 0===ar?void 0:ar.title),textContent:L.isEncrypted?"[Encrypted Content]":L.textContent,_contentVersion:((null===ar||void 0===ar?void 0:ar._contentVersion)||0)+1});if(null!==(f=L)&&void 0!==f&&f.isEncrypted){const e=(null===Or||void 0===Or?void 0:Or.map(e=>e.id))||[];try{const t=await(0,H.YE)(ar.id,e);t&&(U=(0,o.A)((0,o.A)({},t),{},{id:ar.id,title:n||(null===t||void 0===t?void 0:t.title)||(null===ar||void 0===ar?void 0:ar.title),_contentVersion:((null===ar||void 0===ar?void 0:ar._contentVersion)||0)+1}))}catch(R){console.warn("\u26a0\ufe0f Refetch after encrypt failed, UI will show placeholder:",R)}}const M=(0,co.IE)(D),z=(t||"").replace(/<[^>]*>/g,"").trim()||n||"";if(M&&(0,co.Wy)(z))try{const e=await(0,so.V)(z);if(null!==e&&void 0!==e&&e.category&&!(0,co.IE)(e.category)){U=(0,o.A)((0,o.A)({},U),{},{category:e.category,subcategory:e.subcategory||"General"});await Cg(ar.id,e.category,e.subcategory)&&Ie.Ay.success("AI updated the category",{id:co.z1})}}catch(O){console.warn("Category generation failed:",O)}const V=U;Rn(e=>{const t=e.documents.find(e=>e.id===ar.id);if(!t)return e;const n=(0,o.A)((0,o.A)({},t),V);return JSON.stringify(t)!==JSON.stringify(n)?(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===ar.id?n:e)}):e}),ir(e=>{if((null===e||void 0===e?void 0:e.id)!==ar.id)return e;const t=(0,o.A)((0,o.A)({},e),V);return JSON.stringify(e)===JSON.stringify(t)?e:t}),ie.markSaved(c);const J="image"===(null===ar||void 0===ar?void 0:ar.type)||(null===ar||void 0===ar?void 0:ar.fileType)&&String(ar.fileType).startsWith("image/"),q=(0,co.Q4)(n,t);null!==ar&&void 0!==ar&&ar.coverImageUrl||J||!(q.length>=co.cF)||Eg(ar.id,q).catch(()=>{});
1{const e="string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null;if(e&&F.some(t=>String(t)===String(e)))if(V.isEncrypted)xi(e,[],{fromEncryptedPostSave:!0}).catch(e=>console.error("Post-save RAG index:",e));else{const n=(t||"").replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim(),r=(0,o.A)((0,o.A)({},V),{},{textContent:n||V.textContent});xi(e,bi(Bp,r,ar.id)).catch(e=>console.error("Post-save RAG index:",e))}}return(0,W.gg)("\u2705 Document updated successfully with workspaceIds:",F),Un("Saved"),setTimeout(()=>Un(null),900),l(ar.id),(0,o.A)((0,o.A)({},L),{},{id:ar.id})}catch(P){var A,j,N,C;null!==ar&&void 0!==ar&&ar.id&&/^new_|^temp_/.test(String(ar.id))&&(Hs.current.delete(ar.id),(0,W.gg)("\ud83d\udd13 Unlocked document creation for temp ID (error):",ar.id)),console.error("\u274c Save failed:",P),console.error("\u274c Error details:",{message:null===P||void 0===P?void 0:P.message,code:null===P||void 0===P?void 0:P.code,stack:null===P||void 0===P?void 0:P.stack,name:null===P||void 0===P?void 0:P.name,toString:null===P||void 0===P?void 0:P.toString()}),null!==ar&&void 0!==ar&&ar.id&&ie.markSaved(String(ar.id),0);let r="Unknown error",o=!1;if("permission-denied"===(null===P||void 0===P?void 0:P.code)||null!==P&&void 0!==P&&null!==(A=P.message)&&void 0!==A&&A.includes("Missing or insufficient permissions")){var S;r=(null===ar||void 0===ar?void 0:ar.userId)===(null===(S=G.j2.currentUser)||void 0===S?void 0:S.uid)?"You do not have permission to edit this document.":"You have view-only access to this document. Contact the workspace admin to request edit permissions."}else if(null!==P&&void 0!==P&&null!==(j=P.message)&&void 0!==j&&j.includes("invalid nested entity")||null!==P&&void 0!==P&&null!==(N=P.message)&&void 0!==N&&N.includes("Invalid editorJson")||null!==P&&void 0!==P&&null!==(C=P.message)&&void 0!==C&&C.includes("Nesting depth"))r=(null===P||void 0===P?void 0:P.message)||"Your document contains content that is too deeply nested. Please reduce the nesting level of your lists to 5-6 levels maximum and try again.",o=!0;else if("FirestoreDocumentTooLargeError"===(null===P||void 0===P?void 0:P.name)||"invalid-argument"===(null===P||void 0===P?void 0:P.code)&&"string"===typeof(null===P||void 0===P?void 0:P.message)&&/maximum allowed size|exceeds.*limit|document.*too large|payload.*too large|1048576|1\s?MiB/i.test(P.message)){var E;r=(null===P||void 0===P||null===(E=P.message)||void 0===E?void 0:E.trim())||"This document exceeds Firestore's 1 MB limit per document. Split content into another document or remove large pasted blocks.",o=!0}else if("ValidationWarning"===(null===P||void 0===P?void 0:P.name)){var I;if(r=(null===P||void 0===P||null===(I=P.validation)||void 0===I?void 0:I.warning)||(null===P||void 0===P?void 0:P.message)||"Document structure will be modified during save.",null!==P&&void 0!==P&&P.validation)return Bs({dataToSave:e,html:t,title:n,isUpdate:a,isManualSave:i}),qs(P.validation),_s(!0),void Un(null)}else r=(null===P||void 0===P?void 0:P.message)||(null===P||void 0===P?void 0:P.toString())||"Unknown error";throw o?Ie.Ay.error("\u274c Save failed: ".concat(r),{duration:6e3,style:{maxWidth:"500px"}}):Ie.Ay.error("\u274c Save failed: ".concat(r)),Un("Save failed"),setTimeout(()=>Un(null),2e3),P}}(0,i.useEffect)(()=>{(async()=>{const e=new URLSearchParams(window.location.search),t=e.get("sessionId"),n="true"===e.get("isAnonymous"),r=e.get("userId");(0,W.gg)("\ud83d\udd0d URL Parameters:",{sessionId:t,isAnonymous:n,userId:r}),n&&t?((0,W.gg)("\ud83d\udc64 Initializing for anonymous user"),await(async e=>{(0,W.gg)("\ud83d\udc64 Fetching anonymous documents for session:",e),ce(!0);try{const t=(0,B.P)((0,B.rJ)(G.db,"knowledgeBaseDocuments"),(0,B._M)("sessionId","==",e),(0,B._M)("isAnonymous","==",!0)),n=(await(0,B.GG)(t)).docs.map(e=>(0,o.A)({id:e.id},e.data()));(0,W.gg)("\ud83c\udf89 Anonymous documents loaded:",n.length),(0,W.gg)("\ud83d\udcc4 Documents:",n),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:n,processed:!0})),te({uid:e,isAnonymous:!0,email:null})}catch(t){console.error("\u274c Error fetching anonymous documents:",t),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:[],processed:!0}))}finally{ce(!1)}})(t)):r?((0,W.gg)("\ud83d\udc64 Initializing for registered user:",r),X||te({uid:r,isAnonymous:!1})):(0,W.gg)("\u26a0\ufe0f No valid user parameters found")})()},[]),(0,i.useEffect)(()=>
1{if(Pi.current)return;if(!Or||0===Or.length)return void(0,W.gg)("\u23f3 Waiting for workspaces to load...");const e=new URLSearchParams(window.location.search),t=e.get("invited"),n=localStorage.getItem("invitationProcessed");if("true"!==t&&!n)return;Pi.current=!0,(0,W.gg)("\ud83c\udf89 Invitation detected! Selecting invited workspace once...");let r=[];if(n)try{const e=JSON.parse(n);r=Array.isArray(null===e||void 0===e?void 0:e.workspaceIds)?e.workspaceIds.map(String):[]}catch(a){(0,W.gg)("Could not parse invitationProcessed data:",a)}const o=(Or.find(e=>r.includes(String(e.id)))||Or[0]).id;(0,W.gg)("\ud83d\udd27 Setting default workspace from invitation:",o),_o(o);try{localStorage.removeItem("invitationProcessed")}catch(i){}if("true"===t&&"undefined"!==typeof window){e.delete("invited");const t=e.toString(),n="".concat(window.location.pathname).concat(t?"?".concat(t):"").concat(window.location.hash);window.history.replaceState({},"",n)}},[Or]),(0,i.useEffect)(()=>{const e=()=>{const e=window.innerWidth<1024;jn(e),e||Qe(e=>e||!0)};return window.addEventListener("resize",e),e(),()=>{document.body.style.overflow="auto",window.removeEventListener("resize",e)}},[]),(0,i.useEffect)(()=>{const e=e=>!(!e||!e.closest)&&!!(e.closest("[data-editor-area]")||e.closest(".editor-wrapper")||e.closest(".ProseMirror")),t=t=>{var n,r,o;null!==(n=t.dataTransfer)&&void 0!==n&&null!==(r=n.types)&&void 0!==r&&null!==(o=r.includes)&&void 0!==o&&o.call(r,"Files")&&(e(t.target)||t.preventDefault())},n=t=>{var n,r,o;null!==(n=t.dataTransfer)&&void 0!==n&&null!==(r=n.types)&&void 0!==r&&null!==(o=r.includes)&&void 0!==o&&o.call(r,"Files")&&(e(t.target)||(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation()))};return document.addEventListener("dragover",t),document.addEventListener("drop",n),()=>{document.removeEventListener("dragover",t),document.removeEventListener("drop",n)}},[]),(0,i.useEffect)(()=>{Zn&&On.current&&On.current.focus()},[Zn]),(0,i.useEffect)(()=>{if("summary"===Zn&&On.current){const e=On.current;e.style.height="auto",e.style.height="".concat(e.scrollHeight,"px")}},[Zn]),Ss.current=ah;const ih=(0,i.useCallback)(e=>{fs&&Ve?(Ns(e),ws(!0)):e()},[fs,Ve,Ns,ws]),sh=(0,i.useCallback)(()=>{ih(()=>{Je(null),ir(null)})},[ih,Je,ir]);(0,i.useEffect)(()=>{const e=e=>{if(fs&&Ve)return e.preventDefault(),e.returnValue="",""};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}},[fs,Ve]);const lh=(0,i.useCallback)(()=>{const e="new_".concat(Date.now());let t=[];if(Lo&&"Default"!==Lo&&"default"!==Lo){let e;if("string"===typeof Lo?e=Lo:"object"===typeof Lo&&null!==Lo&&(e=Lo.id||Lo._id||Lo.workspaceId),e&&"Default"!==e&&"default"!==e){const n=xd||(null===Or||void 0===Or?void 0:Or.find(t=>t.id===e));n&&"Default Workspace"!==n.name&&(t=[e],(0,W.gg)("\ud83d\udcc1 Pre-populating new document with current workspace:",e,n.name))}}return{newDocId:e,newDoc:(0,o.A)((0,o.A)({id:e,title:"Untitled Document",category:"",workspace:"",workspaceIds:t},El?{folderId:El}:{}),{},{isNew:!0,createdAt:(new Date).toISOString(),updatedAt:(new Date).toISOString(),textContent:"",editorJson:{type:"doc",content:[{type:"heading",attrs:{level:1},content:[{type:"text",text:"Untitled Document"}]},{type:"paragraph",content:[]}]},editorHtml:"<h1>Untitled Document</h1><p></p>",userId:null===Z||void 0===Z?void 0:Z.uid,status:"draft"})}},[Lo,xd,Or,null===Z||void 0===Z?void 0:Z.uid,El]),dh=(0,i.useCallback)(async()=>{var e,t,n;const r=null!==(e=null!==(t=Pn.totalDocumentCount)&&void 0!==t?t:null===(n=Pn.documents)||void 0===n?void 0:n.length)&&void 0!==e?e:0,o="pro"===be||"enterprise"===be,a=o?1/0:10;if((0,W.gg)("\ud83d\udcca Document check:",{currentDocCount:r,userPlan:be,isPro:o,maxDocuments:o?"unlimited":a}),!o&&r>=a)return Ie.Ay.error("Document limit reached! Upgrade to Pro for unlimited documents."),void setTimeout(()=>{window.open("/billing","_blank")},2e3);const i=lh(),s=i.newDocId,l=i.newDoc;ir(l),Je(s),window.innerWidth<1024&&Qe(!1),(0,W.gg)("\ud83d\udcc4 Created new document:",{id:s,isNew:!0,title:l.title,userPlan:be,isPro:o})},[lh,Pn.documents,Pn.totalDocumentCount,be]),ch=(0,i.useCallback)(async()=>{var e,t,n;if(!ls)return void Ie.Ay.error("Enable Env Vault under Based Abilities first");
1if(null===Z||void 0===Z||!Z.uid)return void Ie.Ay.error("Sign in to create an Env Vault");const r=null!==(e=null!==(t=Pn.totalDocumentCount)&&void 0!==t?t:null===(n=Pn.documents)||void 0===n?void 0:n.length)&&void 0!==e?e:0,a="pro"===be||"enterprise"===be;if(!a&&r>=(a?1/0:10))Ie.Ay.error("Document limit reached! Upgrade to Pro for unlimited documents.");else try{let e=[];if(Lo&&"Default"!==Lo&&"default"!==Lo){const t="string"===typeof Lo?Lo:(null===Lo||void 0===Lo?void 0:Lo.id)||(null===Lo||void 0===Lo?void 0:Lo._id)||(null===Lo||void 0===Lo?void 0:Lo.workspaceId);t&&"Default"!==t&&"default"!==t&&(e=[t])}const t=(await(0,re.Tj)({userId:Z.uid,title:"Env Vault",workspaceIds:e,folderId:El||null})).id,n=await(0,H.YE)(t),r=await Q.E.decryptDocument(n,Z.uid,(null===Or||void 0===Or?void 0:Or.map(e=>e.id))||[])||(0,o.A)((0,o.A)({},n),{},{documentKind:"envVault"});ys(!1),ir(r),Je(t),window.innerWidth<1024&&Qe(!1),Ie.Ay.success("Env Vault created")}catch(i){console.error("Create Env Vault failed:",i),Ie.Ay.error((null===i||void 0===i?void 0:i.message)||"Failed to create Env Vault")}},[ls,null===Z||void 0===Z?void 0:Z.uid,Pn.documents,Pn.totalDocumentCount,be,Lo,El,Or]),uh=(0,i.useCallback)(async e=>{if(!e)return"";const t=[],n=null===xd||void 0===xd?void 0:xd.name;n&&t.push("Workspace name: ".concat(n));const r=(null===Z||void 0===Z?void 0:Z.displayName)&&String(Z.displayName).trim()||(null===le||void 0===le?void 0:le.name)&&String(le.name).trim()||"";r&&t.push("User / contact name: ".concat(r)),null!==Z&&void 0!==Z&&Z.email&&t.push("Email: ".concat(Z.email));try{const e=ye||ue;if(e){const n=await(0,Pe.getUserOrganizationData)(e);null!==n&&void 0!==n&&n.name&&t.push("Organization: ".concat(n.name))}}catch(s){}const o=(null===xd||void 0===xd?void 0:xd.address)||(null===xd||void 0===xd?void 0:xd.companyAddress),a=(null===xd||void 0===xd?void 0:xd.phone)||(null===xd||void 0===xd?void 0:xd.companyPhone),i=(null===xd||void 0===xd?void 0:xd.email)||(null===xd||void 0===xd?void 0:xd.companyEmail);return o&&t.push("Address: ".concat(o)),a&&t.push("Phone: ".concat(a)),i&&t.push("Business email: ".concat(i)),t.join("\n")},[xd,Z,le,ye,ue]),mh=(0,i.useCallback)(()=>{var e,t,n;const r=null!==(e=null!==(t=Pn.totalDocumentCount)&&void 0!==t?t:null===(n=Pn.documents)||void 0===n?void 0:n.length)&&void 0!==e?e:0,o="pro"===be||"enterprise"===be;if(!o&&r>=(o?1/0:10))return Ie.Ay.error("Document limit reached! Upgrade to Pro for unlimited documents."),void setTimeout(()=>{window.open("/billing","_blank")},2e3);Cm("form"),qm([]),Qm(null),Bm.current=[],zm.current=null,Xm(null),vm(!0)},[Pn.documents,Pn.totalDocumentCount,be]),ph=Im||"gathering"===Nm||!!$m||np,gh=xp||"gathering"===hp,hh=(0,i.useCallback)(()=>{qm([]),Qm(null),Bm.current=[],zm.current=null,Xm(null)},[]),fh=(0,i.useCallback)(()=>{ph||(vm(!1),Cm("form"),Um([]),Mm.current=null,hh())},[ph,hh]),yh=(0,i.useCallback)(async e=>{if(null===Z||void 0===Z||!Z.uid)throw new Error("You must be signed in to save a PDF document.");if(!(e&&"string"===typeof e.storagePath&&e.storagePath&&"string"===typeof e.downloadUrl&&e.downloadUrl&&"string"===typeof e.markdownPlainText&&e.markdownPlainText.trim()))throw new Error("PDF attachment is incomplete. Re-upload the file.");const t="string"===typeof e.fileName&&e.fileName.trim()?e.fileName.trim():"document.pdf",n=t,r={type:"doc",content:[{type:"heading",attrs:{level:1},content:[{type:"text",text:String(n||"PDF").trim()||"PDF"}]},{type:"paragraph",content:[{type:"text",text:"Original PDF is shown in the viewer."}]}]};const a=function(e){const t=String(e||"PDF").trim().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")||"PDF";return"<h1>".concat(t,"</h1><p>Original PDF is shown in the viewer.</p>")}(n),i=lh(),l=i.newDocId,d=i.newDoc,c=Array.isArray(d.workspaceIds)?[...d.workspaceIds]:[];let u;try{const i={title:n,editorJson:r,editorHtml:a,textContent:e.markdownPlainText,category:"",workspace:d.workspace||"Default",workspaceIds:c,createdAtISO:d.createdAt||(new Date).toISOString(),updatedAtISO:(new Date).toISOString()},s=await Q.E.encryptDocumentContent(i,Z.uid,c);u=(0,o.A)((0,o.A)((0,o.A)({},s),{},{title:n,category:"",workspace:d.workspace||"Default",workspaceIds:c},d.folderId?{folderId:d.folderId}:{}),{},{viewerMode:"pdf",url:e.downloadUrl,previewUrl:e.downloadUrl,fileName:t,fileType:"application/pdf",textContent:"[Encrypted Content]",_editorJsonForPreservation:r,_editorHtmlForPreservation:a,_pdfCanonicalCopy:{storagePath:e.storagePath,fileName:t},_pdfIndexPlaintext:e.markdownPlainText,documentImageUrls:[]})}catch(g){console.warn("PDF viewer doc \u2014 encryption failed, saving unencrypted:",g),u=(0,o.A)((0,o.A)({editorJson:r,editorHtml:a,title:n,textContent:e.markdownPlainText,category:"",workspace:d.workspace||"Default",workspaceIds:c},d.folderId?{folderId:d.folderId}:{}),{},{isEncrypted:!1,viewerMode:"pdf",url:e.downloadUrl,previewUrl:e.downloadUrl,fileName:t,fileType:"application/pdf",documentImageUrls:[],_pdfCanonicalCopy:{storagePath:e.storagePath,fileName:t},_pdfIndexPlaintext:e.markdownPlainText})}const m=(0,o.A)((0,o.A)({},d),{},{id:l,title:n,viewerMode:"pdf",url:e.downloadUrl,previewUrl:e.downloadUrl,fileName:t,fileType:"application/pdf",textContent:e.markdownPlainText,editorJson:r,editorHtml:a,userId:Z.uid,status:"draft"}),p=Ie.Ay.loading("Saving PDF\u2026");try{(0,s.flushSync)(()=>{ir(m),Je(l),window.innerWidth<1024&&Qe(!1)}),sr.current=m;const e=Ss.current;if("function"!==typeof e)throw new Error("Save pipeline is not ready. Try again.");await e(u,a,n,!1,!0,!0),Ie.Ay.success("Document saved",{id:p})}catch(h){throw Ie.Ay.dismiss(p),h}},[lh,Z,ir,Je,Qe]),vh=(0,i.useCallback)(async e=>{if(ph)return;const t=e&&"string"===typeof e.storagePath&&e.storagePath&&"string"===typeof e.downloadUrl&&e.downloadUrl&&"string"===typeof e.markdownPlainText&&e.markdownPlainText.trim()?{storagePath:e.storagePath,downloadUrl:e.downloadUrl,fileName:e.fileName,markdown:"str
1ing"===typeof e.markdown?e.markdown:"",markdownPlainText:e.markdownPlainText}:null,n=e&&"string"===typeof e.markdown?e.markdown.trim():"",r=()=>{var e,t,n;const r=null!==(e=null!==(t=Pn.totalDocumentCount)&&void 0!==t?t:null===(n=Pn.documents)||void 0===n?void 0:n.length)&&void 0!==e?e:0,o="pro"===be||"enterprise"===be;return!(!o&&r>=(o?1/0:10))||(Ie.Ay.error("Document limit reached! Upgrade to Pro for unlimited documents."),setTimeout(()=>{window.open("/billing","_blank")},2e3),!1)};if(t){if(!r())return;vm(!1),Cm("form"),Um([]),Mm.current=null,hh();try{await yh(t)}catch(u){console.error("Open PDF from Create with AI:",u),Ie.Ay.error((null===u||void 0===u?void 0:u.message)||"Could not open PDF document.")}return}if(n&&!r())return;if(vm(!1),Cm("form"),Um([]),Mm.current=null,hh(),!n)return void dh();const a=lh(),i=a.newDocId,s=a.newDoc,l=(0,Jn.rR)(n)||("string"===typeof(null===e||void 0===e?void 0:e.fileName)?e.fileName.replace(/\.pdf$/i,"").trim():"")||"Untitled Document",d=(0,Wn.p)(l,n),c=(0,pa.Br)(d)||"";ir((0,o.A)((0,o.A)({},s),{},{title:l,editorJson:d,textContent:c})),Je(i),window.innerWidth<1024&&Qe(!1),requestAnimationFrame(()=>{try{const e=pm.current;e&&!e.isDestroyed&&(e.commands.setContent(d,!1,{emitUpdate:!1}),e.commands.focus("end"))}catch(u){(0,W.gg)("Blank doc from PDF setContent:",u)}})},[ph,dh,hh,lh,Pn.totalDocumentCount,Pn.documents,be,yh]),xh=(0,i.useCallback)(async(e,t,n)=>{const r=lh(),a=r.newDocId,i=r.newDoc;Dm(!0),Cm("loading"),Om("Gathering insights to create document"),lp.current=!1,sp(!1);const s=(e,t)=>{const n=(0,Jn.rR)(t),r=(0,Wn.p)(n,t),a=(0,pa.Br)(r)||"";ir(t=>t&&t.id===e?(0,o.A)((0,o.A)({},t),{},{title:n,editorJson:r,textContent:a}):t),requestAnimationFrame(()=>{try{const e=pm.current;e&&!e.isDestroyed&&e.commands.setContent(r,!1,{emitUpdate:!1})}catch(e){(0,W.gg)("AI stream setContent:",e)}})};let l,d="";const c=Array.isArray(t)&&t.some(e=>e&&String(e.answer||"").trim())?t.filter(e=>e&&String(e.answer||"").trim()):void 0;try{let t=await uh(e.useCompanyInfo);t=hi(t,e.uploadedDocumentsContext);const r="string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null;if(!0===e.useWorkspaceDocuments&&r){Om("Indexing workspace documents\u2026");try{await xi(r,Bp)}catch(u){console.error("Create with AI \u2014 workspace index:",u)}finally{Om("Gathering insights to create document")}}const g=e.pdfSource;if(g&&"string"===typeof g.storagePath&&g.storagePath&&"string"===typeof g.downloadUrl&&g.downloadUrl&&"string"===typeof g.markdownPlainText&&g.markdownPlainText.trim())return vm(!1),Cm("form"),Um([]),Mm.current=null,hh(),void await yh(g);ir(i),Je(a),window.innerWidth<1024&&Qe(!1);const h={documentType:e.documentType,tone:e.tone,companyContext:t,useCompanyInfo:e.useCompanyInfo,useWorkspaceDocuments:e.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(e.pinnedDocumentIds)?e.pinnedDocumentIds:void 0};await(0,Jn.uV)({userPrompt:e.userPrompt,documentType:e.documentType,tone:e.tone,companyContext:t,workspaceId:r,mode:"create",clarificationAnswers:c,includeWorkspaceDocuments:!0===e.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(e.pinnedDocumentIds)&&e.pinnedDocumentIds.length>0?e.pinnedDocumentIds:void 0,integrationContext:n,onStreamMeta:pi,onResponse:()=>{l=Ie.Ay.loading("Creating your document\u2026"),vm(!1),Cm("form"),Um([]),Mm.current=null,hh()},onDelta:e=>{lp.current||(lp.current=!0,sp(!0)),d+=e,null!=gm.current&&cancelAnimationFrame(gm.current),gm.current=requestAnimationFrame(()=>{gm.current=null,s(a,d)})}}),null!=gm.current&&(cancelAnimationFrame(gm.current),gm.current=null),d=Hn(d),n&&!(0,Tr.uQ)(n,e.userPrompt,e.documentType)&&(d=(0,Tr.d5)(d)),(0,Qn.S0)(n,e.userPrompt,is)||(d=(0,Qn.J_)(d)),s(a,d);const f=(0,Jn.rR)(d);let y=(0,Wn.p)(f,d);const v=(0,Gn.hF)({markdown:d,clarificationPairs:c});y=br(y,{userPrompt:e.userPrompt,integrationContext:n,formsEnabled:is,priorTipTapJson:null}),y=(0,Vn.ec)(y,{documentType:e.documentType,integrationContext:n,counterpartyEmail:v,userPrompt:e.userPrompt});const x=Ir(y,{userPrompt:e.userPrompt,integrationContext:n,documentTitle:f});y=x.editorJson;const b=x.paymentConfig,w=(0,pa.Br)(y)||"";ir(e=>e&&e.id===a?(0,o.A)((0,o.A)({},e),{},{title:f,editorJson:y,textContent:w,aiGeneratedToolbarUntil:Date.now()+1e4,lastAIGenerateOptions:h},b||{}):e),requestAnimationFrame(()=>{try{const e=pm.current;e&&!e.isDestroyed&&(e.commands.setContent(y,!1,{emitUpdate:!1}),e.commands.focus("end"))}catch(u){(0,W.gg)("AI stream final setContent:",u)}
1}),ys(!0);const k=async()=>{await new Promise(e=>requestAnimationFrame(()=>e())),await new Promise(e=>requestAnimationFrame(()=>e()));for(let e=0;e<24;e++){if("function"===typeof Cs.current)return void await Cs.current();await new Promise(e=>setTimeout(e,50))}throw new Error("Editor was not ready to save. Use Save or \u2318S / Ctrl+S.")};try{if(await k(),b&&a)try{await um(a,b)}catch(m){console.error("Create with AI \u2014 payment config:",m)}Ie.Ay.success("Document saved",{id:l})}catch(p){console.error("Create with AI \u2014 save after generate:",p),Ie.Ay.error((null===p||void 0===p?void 0:p.message)||"Generated in the editor but not saved yet. Press Save or \u2318S / Ctrl+S.",{id:l})}}catch(g){console.error("Create with AI:",g);const e=(null===g||void 0===g?void 0:g.details)||(null===g||void 0===g?void 0:g.message)||"",t=String((null===g||void 0===g?void 0:g.code)||"").includes("functions/")||String(e).includes("internal")?"Could not generate the document. Try again in a moment.":e||"Could not generate the document.";null!=l?Ie.Ay.error(t,{id:l}):Ie.Ay.error(t),Je(null),ir(null),Cm("form"),Mm.current=null,Um([]),hh()}finally{null!=gm.current&&(cancelAnimationFrame(gm.current),gm.current=null),Dm(!1),Om(""),lp.current=!1,sp(!1)}},[lh,uh,Lo,xd,Z,hh,Bp,yh,is,um]),bh=(0,i.useCallback)(async(e,t)=>{const n=(0,Pe.getSelectedOrganizationId)()||ue||ye;if(!n)return await xh(e,t,void 0),!1;rp(!0);try{const r=(0,ge.httpsCallable)((0,ge.getFunctions)(),"getAllIntegrationStatuses"),o=(await r({organizationId:n})).data||{},a=(0,Pr.iR)(e.userPrompt,e.documentType);if(0===a.length){const n=(0,Pr.Ks)(o,[],[],gi(e,{}),e.userPrompt,e.documentType);return rp(!1),await xh(e,t,n),!1}return Mm.current=e,zm.current=t,Bm.current=[],Qm(o),qm(a),Cm("integrations"),rp(!1),!0}catch(r){return console.error("Create with AI \u2014 integration snapshot:",r),Ie.Ay.error("Could not load integrations. Continuing without."),rp(!1),await xh(e,t,void 0),!1}},[xh,ue,ye]),wh=(0,i.useCallback)(async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=Mm.current;if(!t)return;const n=zm.current,r=[...Bm.current],o=(0,Pr.Ks)(Km,Jm,r,gi(t,e),t.userPrompt,t.documentType);await xh(t,n,o)},[xh,Km,Jm]),kh=(0,i.useCallback)(async e=>{const t=(0,Pe.getSelectedOrganizationId)()||ue||ye;if(t){Xm(e);try{const n=await(0,Dr.S)(t,e);if(!n.ok)return void Ie.Ay.error(n.errorMessage);Bm.current=[...new Set([...Bm.current,e])];const r=(0,ge.httpsCallable)((0,ge.getFunctions)(),"getAllIntegrationStatuses"),o=await r({organizationId:t});Qm(o.data||{});const a=Pr.u9[e]||e;Ie.Ay.success("".concat(a," is on for this workspace.")),window.dispatchEvent(new Event("organizationChanged"))}finally{Xm(null)}}else Ie.Ay.error("No organization selected.")},[ue,ye]),Ah=(0,i.useCallback)(async e=>{if(!!e.askClarification){Mm.current=e,Cm("gathering"),Om("Checking what details we need\u2026");try{let t=await uh(e.useCompanyInfo);t=hi(t,e.uploadedDocumentsContext);const n="string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null,r=await(0,Jn.Ln)({userPrompt:e.userPrompt,documentType:e.documentType,companyContext:t,workspaceId:n}),o=r.status,a=r.questions;"sufficient"!==o&&a.length?(Um(a),Cm("clarify")):await bh(e,null)}catch(t){console.error("Create with AI \u2014 gather details:",t);const e=(null===t||void 0===t?void 0:t.message)||"Could not prepare questions. Try again or turn off \u201cAsk for missing details\u201d.";Ie.Ay.error(e),Cm("form"),Mm.current=null}finally{Om("")}}else await bh(e,null)},[bh,uh,Lo,xd]),jh=(0,i.useCallback)(async e=>{let t=e.clarificationPairs;const n=Mm.current;n&&await bh(n,t)},[bh]),Nh=(0,i.useCallback)(()=>{Im||(Cm("form"),Um([]),Mm.current=null)},[Im]),Ch=(0,i.useCallback)(()=>{var e;if(null===(e=sr.current)||void 0===e||!e.id)return;const t=lh(),n=t.newDocId,r=t.newDoc;ir((0,o.A)((0,o.A)({},r),{},{id:n,aiGeneratedToolbarUntil:0,lastAIGenerateOptions:void 0,showAIRevisionBar:!1})),Je(n),requestAnimationFrame(()=>{try{const e=pm.current;e&&!e.isDestroyed&&(e.commands.setContent(r.editorJson,!1,{emitUpdate:!1}),e.commands.focus("end"))}catch(e){(0,W.gg)("Start from scratch setContent:",e)}})},[lh]),Sh=(0,i.useCallback)(()=>{Tp(e=>e+1),mp(!0),fp("form"),Ep([]),Rp.current=null},[]),Eh=(0,i.useCallback)(()=>{gh||(mp(!1),fp("form"),Ep([]),Rp.current=null,Mp(""))},[gh]),Ih=(0,i.useCallback)(()=>pm.current,[]),Dh=(0,i.useCallback)(()=>{const e=pm.current;(e&&!e.isDestroyed?String(e.getText()||"").trim():"").length?(Tp(e=>e+1),mp(!0),fp("form"),Ep([]),Rp.current=null):Ie.Ay.error("Add some content to the document first, or describe a change that does not need existing text.")},[]),Ph=(0,i.useCallback)(()=>{ir(e=>e?(0,o.A)((0,o.A)({},e),{},{showAIRevisionBar:!1}):e)},[]),Th=(0,i.useCallback)(()=>{ir(e=>e?(0,o.A)((0,o.A)({},e),{},{aiGeneratedToolbarUntil:0}):e)},[]),Rh=(0,i.useCallback)(async function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=n.onResponse,a=n.fromUpdateModal,i=void 0!==a&&a,s=String(e.userPrompt||"").trim();if(!s)return;const l=sr.current,d=pm.current;if(null===l||void 0===l||!l.id||!d||d.isDestroyed)return void Ie.Ay.error("Editor is not ready.");
1i&&(bp(!0),fp("loading"),jp("Preparing your update\u2026"));const c=Ie.Ay.loading("Revising with AI\u2026");try{const n=d.getJSON();let a=await uh(!1!==e.useCompanyInfo);a=hi(a,e.uploadedDocumentsContext);const p="string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null;if(!0===e.useWorkspaceDocuments&&p)try{await xi(p,Bp)}catch(u){console.error("AI revision \u2014 workspace index:",u)}const g=Array.isArray(t)&&t.some(e=>e&&String(e.answer||"").trim())?t.filter(e=>e&&String(e.answer||"").trim()):void 0,h=l.id;let f="";const y=(0,_e.Od)(l,"Untitled Document"),v=e.documentType||"auto",x=(0,Pr.zc)({formsEnabled:is,documentSignaturesEnabled:es,userPrompt:s,documentType:v}),b=e=>{const t=(0,Jn.rR)(e,y),n=(0,Wn.p)(t,e),r=(0,pa.Br)(n)||"";ir(e=>e&&e.id===h?(0,o.A)((0,o.A)({},e),{},{title:t,editorJson:n,textContent:r}):e),requestAnimationFrame(()=>{try{const e=pm.current;e&&!e.isDestroyed&&e.commands.setContent(n,!1,{emitUpdate:!1})}catch(u){(0,W.gg)("AI revision stream setContent:",u)}})};i&&jp("Updating your document\u2026"),await(0,Jn.uV)({userPrompt:s,documentType:v,tone:e.tone||"professional",companyContext:a,workspaceId:p,mode:"revise",currentTipTapJson:n,clarificationAnswers:g,includeWorkspaceDocuments:!0===e.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(e.pinnedDocumentIds)&&e.pinnedDocumentIds.length>0?e.pinnedDocumentIds:void 0,integrationContext:x.enabled.forms||x.enabled.documentSignatures?x:void 0,onStreamMeta:pi,onResponse:()=>{null===r||void 0===r||r(),i&&(mp(!1),fp("form"),Ep([]),Rp.current=null)},onDelta:e=>{f+=e,null!=gm.current&&cancelAnimationFrame(gm.current),gm.current=requestAnimationFrame(()=>{gm.current=null,b(f)})}}),null!=gm.current&&(cancelAnimationFrame(gm.current),gm.current=null),f=Hn(f),x&&!(0,Tr.uQ)(x,s,v)&&(f=(0,Tr.d5)(f)),(0,Qn.S0)(x,s,is)||(f=(0,Qn.J_)(f)),b(f);const w=(0,Jn.rR)(f,y);let k=(0,Wn.p)(w,f);const A=(0,Gn.hF)({markdown:f,clarificationPairs:g});k=br(k,{userPrompt:s,integrationContext:x,formsEnabled:is,priorTipTapJson:n}),k=(0,Vn.ec)(k,{documentType:v,integrationContext:x,counterpartyEmail:A,userPrompt:s});const j=Ir(k,{userPrompt:s,integrationContext:x,documentTitle:w});k=j.editorJson;const N=(0,pa.Br)(k)||"",C={documentType:v,tone:e.tone||"professional",companyContext:a,useCompanyInfo:!1!==e.useCompanyInfo,useWorkspaceDocuments:!0===e.useWorkspaceDocuments,pinnedDocumentIds:Array.isArray(e.pinnedDocumentIds)?e.pinnedDocumentIds:void 0};if(ir(e=>e&&e.id===h?(0,o.A)((0,o.A)({},e),{},{title:w,editorJson:k,textContent:N,showAIRevisionBar:!1,aiGeneratedToolbarUntil:Date.now()+1e4,lastAIGenerateOptions:C},j.paymentConfig||{}):e),requestAnimationFrame(()=>{try{const e=pm.current;e&&!e.isDestroyed&&(e.commands.setContent(k,!1,{emitUpdate:!1}),e.commands.focus("end"))}catch(u){(0,W.gg)("AI revision final setContent:",u)}}),j.paymentConfig&&h)try{await um(h,j.paymentConfig)}catch(m){console.error("AI revision \u2014 payment config:",m)}Ie.Ay.success("Document updated",{id:c})}catch(p){console.error("AI revision:",p);const e=(null===p||void 0===p?void 0:p.details)||(null===p||void 0===p?void 0:p.message)||"";Ie.Ay.error(String((null===p||void 0===p?void 0:p.code)||"").includes("functions/")?"Could not revise the document. Try again.":e||"Could not revise the document.",{id:c})}finally{null!=gm.current&&(cancelAnimationFrame(gm.current),gm.current=null),i&&(bp(!1),fp("form"),jp(""))}},[uh,Lo,xd,Bp,es,is]),Oh=(0,i.useCallback)(async e=>{if(!!!e.askClarification)return void await Rh(e,null,{fromUpdateModal:!0});const t=pm.current;if(!t||t.isDestroyed)return void Ie.Ay.error("Editor is not ready.");const n=String(t.getText()||"").trim();if(!n)return void Ie.Ay.error("Add some content to the document before updating with AI.");const r=n.slice(0,Jn.s$);Rp.current=e,fp("gathering"),jp("Checking what details we need\u2026");try{let t=await uh(e.useCompanyInfo);t=hi(t,e.uploadedDocumentsContext);const n="string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null,o=await(0,Jn.Ln)({userPrompt:e.userPrompt,documentType:e.documentType,companyContext:t,workspaceId:n,mode:"revise",documentExcerpt:r}),a=o.status,i=o.questions;"sufficient"!==a&&i.length?(Ep(i),fp("clarify")):await Rh(e,null,{fromUpdateModal:!0})}catch(o){console.error("Update with AI \u2014 gather details:",o);const e=(null===o||void 0===o?void 0:o.message)||"Could not prepare questions. Try again or turn off \u201cAsk for missing details\u201d.";Ie.Ay.error(e),fp("form"),Rp.current=null}finally{jp("")}},[uh,Lo,xd,Rh]),Fh=(0,i.useCallback)(async e=>{let t=e.clarificationPairs;const n=Rp.current;n&&await Rh(n,t,{fromUpdateModal:!0})},[Rh]),Lh=(0,i.useCallback)(()=>{xp||(fp("form"),Ep([]),Rp.current=null)},[xp]);(0,i.useEffect)(()=>{const e=Oe("createWithAI",async e=>{var t,n,r;const o=null===e||void 0===e?void 0:e.form,a=String((null===o||void 0===o?void 0:o.userPrompt)||"").trim();if(!o||!a)return;const i=null!==(t=null!==(n=Pn.totalDocumentCount)&&void 0!==n?n:null===(r=Pn.documents)||void 0===r?void 0:r.length)&&void 0!==t?t:0,s="pro"===be||"enterprise"===be;if(!s&&i>=(s?1/0:10))return Ie.Ay.error("Document limit reached! Upgrade to Pro for unlimited documents."),void setTimeout(()=>{window.open("/billing","_blank")},2e3);const l=Array.isArray(null===e||void 0===e?void 0:e.clarificationPairs)?e.clarificationPairs:null;await bh(o,l)&&vm(!0)}),t=Oe("openBlank",()=>{dh()}),n=Oe("openDocumentById",e=>{let t=e.id;const n=null!=t?String(t).trim():"";if(!n)return;Array.isArray(Pn.documents)&&Pn.documents.some(e=>String(e.id)===n)||Array.isArray(Bp)&&Bp.some(e=>String(e.id)===n)?Je(n):Ie.Ay.error("That document is not in this workspace.")}),r=Oe("updateWithAIForCurrent",async e=>{let t=e.userPrompt;
1const n=String(t||"").trim(),r=pm.current;(r&&!r.isDestroyed?String(r.getText()||"").trim():"").length?await Rh(Fp(n),null,{fromUpdateModal:!1}):Ie.Ay.error("Open a document with content first, or describe a change that does not need existing text.")}),o=Oe("updateWithAIForDocument",async e=>{let t=e.id,n=e.userPrompt;const r=null!=t?String(t).trim():"",o=String(n||"").trim();if(!r)return;if(!(Array.isArray(Pn.documents)&&Pn.documents.some(e=>String(e.id)===r)||Array.isArray(Bp)&&Bp.some(e=>String(e.id)===r)))return void Ie.Ay.error("That document is not in this workspace.");Je(r),await new Promise(e=>setTimeout(e,500));const a=pm.current;(a&&!a.isDestroyed?String(a.getText()||"").trim():"").length?await Rh(Fp(o),null,{fromUpdateModal:!1}):Ie.Ay.error("Could not load document content yet. Open the document and try again from Based AI.")}),a=Oe("switchWorkspace",e=>{let t=e.workspaceId;const n=null!=t?String(t).trim():"";if(!n)return;Array.isArray(Or)&&Or.some(e=>String(e.id)===n)?(_o(n),Bo("workspace"),Je(null)):Ie.Ay.error("That workspace is not available.")}),i=Oe("startTimerOnDocument",async e=>{let t=e.id,n=e.taskName,r=e.forceSwitchTimer;const o=null!=t?String(t).trim():"",a=String(n||"").trim();if(!o||!a)return;if(!$i)return void Ie.Ay.error("Enable Timer in Integrations to start timing from Based AI.");Array.isArray(Pn.documents)&&Pn.documents.some(e=>String(e.id)===o)||Array.isArray(Bp)&&Bp.some(e=>String(e.id)===o)?(r&&(0,se.HG)(null),Bo("workspace"),Je(o),setTimeout(()=>{Tt(a)},650)):Ie.Ay.error("That document is not in this workspace.")}),s=Oe("openBlankThenStartTimer",async e=>{let t=e.taskName,n=e.forceSwitchTimer;const r=String(t||"").trim();r&&($i?(n&&(0,se.HG)(null),Nt.current={taskName:r},await dh()):Ie.Ay.error("Enable Timer in Integrations to start timing from Based AI."))});return()=>{e(),t(),n(),r(),o(),a(),i(),s()}},[Oe,bh,Rh,Fp,dh,Je,_o,Bo,Pn.documents,Pn.totalDocumentCount,be,Bp,vm,Or,$i]);const _h=(0,i.useCallback)(async e=>{const t=String(e||"").trim();if(!t)return;const n=sr.current;if(null===n||void 0===n||!n.id)return void Ie.Ay.error("Editor is not ready.");const r=n.lastAIGenerateOptions||{};await Rh({userPrompt:t,documentType:r.documentType||"auto",tone:r.tone||"professional",useCompanyInfo:!1!==r.useCompanyInfo,useWorkspaceDocuments:!0===r.useWorkspaceDocuments},null,{})},[Rh]);(0,i.useEffect)(()=>{jt.current=!1},[Le.search]),(0,i.useEffect)(()=>{if(jt.current)return;if(!Or||0===Or.length)return;if(null===X||void 0===X||!X.uid||X.isAnonymous)return;const e=new URLSearchParams(Le.search);if("1"!==e.get("welcomeNewDoc"))return;jt.current=!0,dh(),e.delete("welcomeNewDoc");const t=e.toString();Fe({pathname:"/",search:t?"?".concat(t):""},{replace:!0})},[Le.search,Or,null===X||void 0===X?void 0:X.uid,null===X||void 0===X?void 0:X.isAnonymous,dh,Fe]);const Uh=(0,i.useRef)(!1);(0,i.useEffect)(()=>{Uh.current=!1},[Le.search]),(0,i.useEffect)(()=>{if(Uh.current)return;if(!Or||0===Or.length)return;if(null===X||void 0===X||!X.uid||X.isAnonymous)return;const e=new URLSearchParams(Le.search);if(!("1"===e.get("fabPendingAction")||"1"===e.get("fabOpenBlank")||"1"===e.get("fabOpenBlankThenStartTimer")||!!e.get("fabOpenDocId")||!!e.get("fabUpdateDocId")||!!e.get("fabStartTimerDocId")||!!e.get("fabSwitchWorkspaceId")))return;if(Uh.current=!0,"1"===e.get("fabPendingAction")){e.delete("fabPendingAction");try{const e=sessionStorage.getItem("kbFabPendingAction");if(e){var t,n,r;const c=JSON.parse(e);if(sessionStorage.removeItem("kbFabPendingAction"),"createWithAI"===(null===c||void 0===c?void 0:c.type)&&null!==(t=c.payload)&&void 0!==t&&t.form){var o,a,i;const e=null!==(o=null!==(a=Pn.totalDocumentCount)&&void 0!==a?a:null===(i=Pn.documents)||void 0===i?void 0:i.length)&&void 0!==o?o:0,t="pro"===be||"enterprise"===be;!t&&e>=(t?1/0:10)?Ie.Ay.error("Document limit reached! Upgrade to Pro for unlimited documents."):xh(c.payload.form,c.payload.clarificationPairs||null,null)}else if("updateWithAIDocument"===(null===c||void 0===c?void 0:c.type)&&null!==(n=c.payload)&&void 0!==n&&n.id){const e=String(c.payload.id),t=String(c.payload.userPrompt||"").trim();Array.isArray(Pn.documents)&&Pn.documents.some(t=>String(t.id)===e)||Array.isArray(Bp)&&Bp.some(t=>String(t.id)===e)?(Je(e),setTimeout(()=>{const e=pm.current;(e&&!e.isDestroyed?String(e.getText()||"").trim():"").length?Rh(Fp(t),null,{fromUpdateModal:!1}):Ie.Ay.error("Could not load document content yet. Try opening the document from the list.")},550)):Ie.Ay.error("That document is not in this workspace.")}else if("updateWithAIForCurrent"===(null===c||void 0===c?void 0:c.type)){var s;const e=String((null===(s=c.payload)||void 0===s?void 0:s.userPrompt)||"").trim();setTimeout(()=>{const t=pm.current;(t&&!t.isDestroyed?String(t.getText()||"").trim():"").length?Rh(Fp(e),null,{fromUpdateModal:!1}):Ie.Ay.error("Open a document first, then try your update again from Based AI.")},300)}else if("startTimerOnDocument"===(null===c||void 0===c?void 0:c.type)&&null!==(r=c.payload)&&void 0!==r&&r.id){const e=String(c.payload.id).trim(),t=String(c.payload.taskName||"").trim();if($i){c.payload.forceSwitchTimer&&(0,se.HG)(null);Array.isArray(Pn.documents)&&Pn.documents.some(t=>String(t.id)===e)||Array.isArray(Bp)&&Bp.some(t=>String(t.id)===e)?(Bo("workspace"),Je(e),setTimeout(()=>Tt(t),650)):Ie.Ay.error("That document is not in this workspace.")}else Ie.Ay.error("Enable Timer in Integrations to start timing from Based AI.")}else if("openBlankThenStartTimer"===(null===c||void 0===c?void 0:c.type)){var l;const e=String((null===(l=c.payload)||void 0===l?void 0:l.taskName)||"").trim();if($i){if(e){var d;null!==(d=c.payload)&&void 0!==d&&d.forceSwitchTimer&&(0,se.HG)(null),Nt.current={taskName:e},dh()}}else Ie.Ay.error("Enable Timer in Integrations to start timing from Based AI.")}}}catch(y){console.error("FAB deep link \u2014 pending action:",y)}}if("1"===e.get("fabOpenBlank")&&(e.delete("fabOpenBlank"),dh()),"1"===e.get("fabOpenBlankThenStartTimer")){e.delete("fabOpenBlankThenStartTimer");try{const e=sessionStorage.getItem("kbFabPendingAction");if(e){const t=JSON.parse(e);if(sessionStorage.removeItem("kbFabPendingAction"),"openBlankThenStartTimer"===(null===t||void 0===t?void 0:t.type)){var c;const e=String((null===(c=t.payload)||void 0===c?void 0:c.taskName)||"").trim();if($i){if(e){var u;null!==(u=t.payload)&&void 0!==u&&u.forceSwitchTimer&&(0,se.HG)(null),Nt.current={taskName:e},dh()}}else Ie.Ay.error("Enable Timer in Integrations to start timing from Based AI.")}}}catch(y){console.error("FAB deep link \u2014 openBlankThenStartTimer:",y)}}const m=e.get("fabSwitchWorkspaceId");if(m){e.delete("fabSwitchWorkspaceId");const t=String(m).trim();Array.isArray(Or)&&Or.some(e=>String(e.id)===t)?(_o(t),Bo("workspace"),Je(null)):Ie.Ay.error("That workspace is not available.")}if(e.get("fabStartTimerDocId")){e.delete("fabStartTimerDocId");try{const e=sessionStorage.getItem("kbFabPendingAction");if(e){var p;const t=JSON.parse(e);if(sessionStorage.removeItem("kbFabPendingAction"),"startTimerOnDocument"===(null===t||void 0===t?void 0:t.type)&&null!==(p=t.payload)&&void 0!==p&&p.id){const e=String(t.payload.id).trim(),n=String(t.payload.taskName||"").trim();if($i){t.payload.forceSwitchTimer&&(0,se.HG)(null);Array.isArray(Pn.documents)&&Pn.documents.some(t=>String(t.id)===e)||Array.isArray(Bp)&&Bp.some(t=>String(t.id)===e)?(Bo("workspace"),Je(e),setTimeout(()=>Tt(n),650)):Ie.Ay.error("That document is not in this workspace.")}else Ie.Ay.error("Enable Timer in Integrations to start timing from Based AI.")}}}catch(y){console.error("FAB deep link \u2014 startTimerOnDocument:",y)}}const g=e.get("fabOpenDocId");if(g){e.delete("fabOpenDocId");const t=String(g).trim();Array.isArray(Pn.documents)&&Pn.documents.some(e=>String(e.id)===t)||Array.isArray(Bp)&&Bp.some(e=>String(e.id)===t)?Je(t):Ie.Ay.error("That document is not in this workspace.")}const h=e.get("fabUpdateDocId");if(h){e.delete("fabUpdateDocId");let t=e.get("fabUpdatePrompt")||"";e.delete("fabUpdatePrompt");try{const e=sessionStorage.getItem("kbFabUpdatePrompt");e&&(t=e,sessionStorage.removeItem("kbFabUpdatePrompt"))}catch(v){}const n=String(h).trim();if(Array.isArray(Pn.documents)&&Pn.documents.some(e=>String(e.id)===n)||Array.isArray(Bp)&&Bp.some(e=>String(e.id)===n)){Je(n);const e=String(t||"").trim();setTimeout(()=>{const t=pm.current;(t&&!t.isDestroyed?String(t.getText()||"").trim():"").length?Rh(Fp(e),null,{fromUpdateModal:!1}):Ie.Ay.error("Could not load document content yet.")},550)}else Ie.Ay.error("That document is not in this workspace.")}const f=e.toString();Fe({pathname:"/",search:f?"?".concat(f):""},{replace:!0})},[Le.search,Or,null===X||void 0===X?void 0:X.uid,null===X||void 0===X?void 0:X.isAnonymous,Fe,Ve,Pn.documents,Pn.totalDocumentCount,be,Bp,xh,dh,Je,Rh,Fp,$i,Tt,Bo,_o]);const Mh=(0,i.useRef)(!1);(0,i.useEffect)(()=>{Mh.current=!1},[Le.search]),(0,i.useEffect)(()=>
1{if(Mh.current)return;if(!Or||0===Or.length)return;if(null===X||void 0===X||!X.uid||X.isAnonymous)return;const e=new URLSearchParams(Le.search);if("1"!==e.get("createWithAI"))return;Mh.current=!0;const t=e.get("aiPrompt")||"",n=e.get("orgId")||null;n&&n!==(0,Pe.getSelectedOrganizationId)()&&((0,Pe.t6)(n),ve(n),fe(n),window.dispatchEvent(new CustomEvent("organizationChanged",{detail:{organizationId:n}}))),km(t),Cm("form"),vm(!0),e.delete("createWithAI"),e.delete("aiPrompt"),e.delete("orgId");const r=e.toString();Fe({pathname:"/",search:r?"?".concat(r):""},{replace:!0})},[Le.search,Or,null===X||void 0===X?void 0:X.uid,null===X||void 0===X?void 0:X.isAnonymous,Fe,ve,fe]),(0,i.useEffect)(()=>{null!==X&&void 0!==X&&X.uid||(jt.current=!1,Mh.current=!1,Uh.current=!1)},[null===X||void 0===X?void 0:X.uid]),(0,i.useEffect)(()=>{const e=e=>{if("Escape"===e.key){if(ym&&!Im&&"gathering"!==Nm&&!$m&&!np)return"clarify"===Nm?(Cm("form"),Um([]),void(Mm.current=null)):"integrations"===Nm?(vm(!1),Cm("form"),Mm.current=null,qm([]),Qm(null),Bm.current=[],void(zm.current=null)):(vm(!1),Cm("form"),Um([]),Mm.current=null,qm([]),Qm(null),Bm.current=[],void(zm.current=null));if(up&&!xp&&"gathering"!==hp)return"clarify"===hp?(fp("form"),Ep([]),void(Rp.current=null)):(mp(!1),fp("form"),Ep([]),void(Rp.current=null));if(null!==ar&&void 0!==ar&&ar.showAIRevisionBar)return void Ph();if(Zn)return void $n(null);if(Fu)return void Lu(!1);if(tr)return void nr(!1);if(Xt)return void nn(null);if(Ve)return void(fs?(Ns(()=>()=>{ir(null),Je(null)}),ws(!0)):(ir(null),Je(null)));if(Tl)return void Rl(null);if(El)return void Il(null);if(An&&Ke)return void Qe(!1)}};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[Zn,Fu,tr,Xt,Ve,An,Ke,fs,Ns,ws,ym,Im,Nm,$m,np,up,xp,hp,null===ar||void 0===ar?void 0:ar.showAIRevisionBar,Ph,Tl,El]),(0,i.useEffect)(()=>{const e=e=>{if("n"===e.key||"N"===e.key){const t=document.activeElement;if("INPUT"===(null===t||void 0===t?void 0:t.tagName)||"TEXTAREA"===(null===t||void 0===t?void 0:t.tagName)||(null===t||void 0===t?void 0:t.isContentEditable)||(null===t||void 0===t?void 0:t.closest('[contenteditable="true"]'))||(null===t||void 0===t?void 0:t.closest(".ProseMirror")))return;if(e.ctrlKey||e.metaKey||e.altKey||e.shiftKey)return;e.preventDefault(),dh()}};return document.addEventListener("keydown",e),()=>{document.removeEventListener("keydown",e)}},[dh]),(0,i.useEffect)(()=>{const e=e=>{Kh.current&&!Kh.current.contains(e.target)&&tt(!1);const t=document.querySelector('[data-toc-dropdown="true"]'),n=t&&t.contains(e.target),r=Ic.current&&Ic.current.contains(e.target),o=yu.current&&yu.current.contains(e.target);if(n||r||o||!jc||Nc(!1),Uu){(0,W.gg)("\ud83d\udfe0 Click detected while share menu open, checking if should close...");const t=document.querySelector('[data-share-menu="true"]'),n=document.querySelector('[data-share-menu-desktop="true"]'),r=An?t:n,o=r&&r.contains(e.target),a=Oc.current&&Oc.current.contains(e.target),i=e.target.closest('[role="menuitem"]');(0,W.gg)("\ud83d\udfe0 Click analysis:",{isMobile:An,menuElement:!!r,isClickInShareMenu:o,isClickInShareButton:a,isClickOnShareMenuButton:!!i,targetTagName:e.target.tagName,targetClassName:e.target.className}),o||a||i?(0,W.gg)("\ud83d\udfe0 Not closing menu - click is inside"):((0,W.gg)("\ud83d\udfe0 Closing share menu due to outside click"),Mu(!1))}};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Uu,An,jc]),(0,i.useEffect)(()=>{const e=()=>{(0,W.gg)("\ud83e\uddf9 Clearing document drag state"),dl(null),pl(null)};return window.addEventListener("clearDocumentDragState",e),()=>{window.removeEventListener("clearDocumentDragState",e)}},[]),(0,i.useEffect)(()=>{const e=e=>{var t,n,r;const o=null===e||void 0===e||null===(t=e.detail)||void 0===t?void 0:t.documentIds,a=null!==(n=null===e||void 0===e||null===(r=e.detail)||void 0===r?void 0:r.folderId)&&void 0!==n?n:null;Array.isArray(o)&&0!==o.length&&Gp(o,a)};return window.addEventListener("documentFolderLocalUpdate",e),()=>
1{window.removeEventListener("documentFolderLocalUpdate",e)}},[Gp]);const zh=e=>{(0,W.gg)("Switching view mode to:",e),cn(e)},Bh=async()=>{try{await(0,he.CI)(G.j2),window.location.href="/",(0,W.gg)("User logged out successfully")}catch(e){console.error("Error signing out:",e)}},Wh=null===(t=G.j2.currentUser)||void 0===t?void 0:t.uid,Vh=q(Wh),Jh=Vh.favorites,qh=Vh.loading,Hh=Vh.isFavorite,Gh=async e=>{try{Hh(e.id)?await J(Wh,e.id):await V(Wh,e),window.location.reload()}catch(t){console.error("Error toggling favorite:",t)}},Kh=(0,i.useRef)(null),Qh=e=>{Qt((0,o.A)((0,o.A)({},Kt),{},{[e]:!Kt[e]}))},Yh=()=>{Qe(e=>{const t=!e;return An&&(document.body.style.overflow=t?"hidden":"auto"),t})},Zh=async(e,t)=>{var n;null===e||void 0===e||null===(n=e.preventDefault)||void 0===n||n.call(e);const r=("string"===typeof t?t:dt).trim();if(!r)return void qt();"string"===typeof t&&t!==dt&&ct(t);const o=++At.current;vt(!0),kt(!0);try{const e=await(0,H.mR)(r,Or);if(At.current!==o)return;gt(e),(0,W.gg)("results1",e)}catch(a){if(console.error("Search error:",a),At.current!==o)return;gt([])}finally{At.current===o&&vt(!1)}};(0,i.useEffect)(()=>{if(!dt.trim())return At.current+=1,gt([]),kt(!1),void vt(!1);const e=setTimeout(async()=>{(0,W.gg)("\ud83d\udd0d Triggering search for:",dt),(0,W.gg)("\ud83d\udd0d Workspace list:",Or);const e=++At.current;vt(!0),kt(!0);try{const t=await(0,H.mR)(dt,Or);if(At.current!==e)return;(0,W.gg)("\ud83d\udd0d Search returned results:",t),(0,W.gg)("\ud83d\udd0d Number of results:",(null===t||void 0===t?void 0:t.length)||0),gt(t),(0,W.gg)("Search results:",t)}catch(t){if(console.error("Search error:",t),At.current!==e)return;gt([])}finally{At.current===e&&vt(!1)}},300);return()=>clearTimeout(e)},[dt,Or]);const $h=(0,i.useCallback)(async()=>{var e,t;if((0,W.gg)("\ud83d\udd0d getCurrentDocument called for currentPage:",Ve),null!==Ve&&void 0!==Ve&&Ve.startsWith("new_")){var n,r,a;(0,W.gg)("\u2728 Creating new document template for:",Ve);let e=[];
1if(Lo&&"Default"!==Lo&&"default"!==Lo){let t;if("string"===typeof Lo?t=Lo:"object"===typeof Lo&&null!==Lo&&(t=Lo.id||Lo._id||Lo.workspaceId),t&&"Default"!==t&&"default"!==t){const n=xd||(null===Or||void 0===Or?void 0:Or.find(e=>e.id===t));n&&"Default Workspace"!==n.name&&(e=[t],(0,W.gg)("\ud83d\udcc1 Pre-populating new document template with current workspace:",t,n.name))}}const t={id:Ve,title:"Untitled Document",fileName:"Untitled Document",textContent:"",category:"",workspace:"",workspaceIds:e,editorJson:{type:"doc",content:[{type:"heading",attrs:{level:1},content:[{type:"text",text:"Untitled Document"}]},{type:"paragraph",content:[]}]},isNew:!0,fileType:"text/plain",uploadedAt:Date.now(),userId:null===Z||void 0===Z?void 0:Z.uid,workspaceId:null},i=null===Pn||void 0===Pn||null===(n=Pn.documents)||void 0===n?void 0:n.find(e=>e.id===Ve);return i?(0,o.A)((0,o.A)((0,o.A)({},t),i),{},{id:Ve,isNew:!0,editorJson:null!==(r=i.editorJson)&&void 0!==r?r:t.editorJson,editorHtml:null!==(a=i.editorHtml)&&void 0!==a?a:t.editorHtml}):t}if(!Ve)return(0,W.gg)("\u274c No current page"),null;let i=(null===Pn||void 0===Pn||null===(e=Pn.documents)||void 0===e?void 0:e.find(e=>e.id===Ve))||null;if(!i)try{const e=await(0,B.getDoc)((0,B.doc)(G.db,"knowledgeBaseDocuments",Ve));e.exists()&&(i=(0,o.A)({id:e.id},e.data()),(0,W.gg)("\ud83d\udcc4 Loaded document by id (not in filtered knowledgeBase):",Ve))}catch(u){console.warn("\u274c Failed to fetch document by id:",Ve,u)}if(!i)return console.warn("\u274c Document not found in knowledgeBase for currentPage:",Ve),null;(0,W.gg)("\ud83d\udd0d FOUND DOCUMENT IN KNOWLEDGEBASE:",{id:i.id,title:i.title,isEncrypted:i.isEncrypted,encryptionMethod:i.encryptionMethod,hasUserEncrypted:!!i.userEncryptedResult,hasLegacyEncrypted:!!i.encryptedResult,hasWorkspaceEncrypted:!!i.workspaceEncryptedResults});const s=i;(0,W.gg)("\u2705 Source document data:",{id:s.id||Ve,title:s.title,workspace:s.workspace,workspaceIds:s.workspaceIds,category:s.category,isEncrypted:s.isEncrypted,source:"knowledgeBase"});let l=(0,o.A)((0,o.A)({},s),{},{id:Ve});const d=(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({id:Ve,category:s.category,workspace:s.workspace,workspaceIds:s.workspaceIds,createdAt:s.createdAt,updatedAt:s.updatedAt,userId:s.userId,workspaceId:s.workspaceId,isEncrypted:s.isEncrypted,uploadedAt:s.uploadedAt,fileName:s.fileName,fileType:s.fileType,type:s.type},void 0!==s.locked&&{locked:s.locked}),void 0!==s.viewerMode&&null!==s.viewerMode?{viewerMode:s.viewerMode}:{}),"string"===typeof s.url&&s.url?{url:s.url}:{}),"string"===typeof s.previewUrl&&s.previewUrl?{previewUrl:s.previewUrl}:{}),void 0!==s.budgetedHours?{budgetedHours:s.budgetedHours}:{}),void 0!==s.totalTimeLogged?{totalTimeLogged:s.totalTimeLogged}:{}),Array.isArray(s.timeEntries)?{timeEntries:s.timeEntries}:{});if((0,W.gg)("\ud83d\udd12 Firestore unencrypted fields:",{id:d.id,workspace:d.workspace,workspaceIds:d.workspaceIds,category:d.category}),l.isEncrypted&&Z)try{const e=(null===Or||void 0===Or?void 0:Or.map(e=>String(e.id)))||[],t=await Q.E.decryptDocument(l,Z.uid,e);if(!t)return console.warn("\u274c Decryption returned null or failed"),(0,o.A)({_decryptionFailed:!0,id:Ve},d);l=(0,o.A)((0,o.A)({},t),d),(0,W.gg)("\u2705 Document decrypted using encryption service:",{id:l.id,category:l.category,workspace:l.workspace,workspaceIds:l.workspaceIds,title:l.title,hasEditorJson:!!l.editorJson,locked:l.locked})}catch(m){return console.error("\u274c Failed to decrypt document:",m),(0,o.A)({_decryptionFailed:!0,id:Ve},d)}else{try{l=await(0,$.fX)(l)}catch(u){console.error("\u274c Failed to hydrate plain-text document content from Storage:",u)}l=(0,o.A)((0,o.A)({},l),d),(0,W.gg)("\ud83d\udcc4 Non-encrypted document, using Firestore data:",{workspace:l.workspace,workspaceIds:l.workspaceIds,category:l.category})}const c=(0,o.A)((0,o.A)({},l),{},{id:Ve,isNew:!1});return(0,W.gg)("\ud83c\udfaf Final document workspace info:",{workspace:c.workspace,workspaceId:c.workspaceId,workspaceIds:c.workspaceIds,matchesFirestore:c.workspace===d.workspace&&JSON.stringify(c.workspaceIds)===JSON.stringify(d.workspaceIds)}),(0,W.gg)("\ud83d\udd0d FINAL DOCUMENT BEING RETURNED:",{id:c.id,title:c.title,hasEditorJson:!!c.editorJson,hasEditorHtml:!!c.editorHtml,hasTextContent:!!c.textContent,editorJsonType:null===(t=c.editorJson)||void 0===t?void 0:t.type,isEncrypted:c.isEncrypted,isDecrypted:c.isDecrypted}),c},[Ve,Z,null===Pn||void 0===Pn?void 0:Pn.documents,Lo,xd,Or]);(0,i.useEffect)(()=>{const e=async e=>{const t=e.detail.documentId;if(t===Ve){(0,W.gg)("\ud83d\udd04 Version restored, reloading document:",t);try{const e=(null===ar||void 0===ar?void 0:ar.workspaceIds)||(Lo?[Lo]:[]),n=await(0,H.YE)(t,e);n?(n.workspaceIds&&Array.isArray(n.workspaceIds)&&n.workspaceIds.length>0&&!n.workspaceId&&(n.workspaceId=n.workspaceIds[0]),ir(n),null!==Pn&&void 0!==Pn&&Pn.documents&&Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===t?n:e)})),(0,W.gg)("\u2705 Document reloaded after version restoration")):console.error("\u274c Failed to reload document after version restoration")}catch(n){console.error("\u274c Error reloading document after version restoration:",n)}}};return window.addEventListener("documentVersionRestored",e),()=>{window.removeEventListener("documentVersionRestored",e)}},[Ve,Pn,ar,Lo]),(0,i.useEffect)(()=>{Ve?(mr(!0),Ys.current.set(Ve,!1),$h().then(e=>{Ys.current.set(Ve,!0),(0,W.v4)("\ud83d\udcf1 getCurrentDocument completed",{currentPage:Ve,docId:null===e||void 0===e?void 0:e.id,docHasEditorJson:!(null===e||void 0===e||!e.editorJson),docIsEncrypted:null===e||void 0===e?void 0:e.isEncrypted,matchesCurrentPage:(null===e||void 0===e?void 0:e.id)===Ve}),e&&e.id===Ve?null!==e&&void 0!==e&&e.editorJson||(0,oe.z7)(e)||null===e||void 0===e||!e.isDecrypted?((0,W.gg)("SETTING CURRENT DOC FROM getCurrentDocument:",{id:null===e||void 0===e?void 0:e.id,title:null===e||void 0===e?void 0:e.title,hasEditorJson:!(null===e||void 0===e||!e.editorJson),isEnvVault:(0,oe.z7)(e),isDecrypted:null===e||void 0===e?void 0:e.isDecrypted,isEncrypted:null===e||void 0===e?void 0:e.isEncrypted,encryptionMethod:null===e||void 0===e?void 0:e.encryptionMethod,matchesCurrentPage:e.id===Ve}),!e.isEncrypted||e.editorJson||(0,oe.z7)(e)||(console.warn("\u26a0\ufe0f WARNING: Encrypted document loaded without decrypted editorJson - onSnapshot may overwrite this"),(0,W.gg)("\u26a0\ufe0f Encrypted document missing editorJson - this may cause content loss if onSnapshot fires")),ir(t=>{const n=(null===Ve||void 0===Ve?void 0:Ve.startsWith("new_"))&&!0===e.isNew&&"Untitled Document"===e.title&&"pdf"!==e.viewerMode;if(t&&t.id===Ve&&n&&("pdf"===t.viewerMode||"string"===typeof t.textContent&&t.textContent.trim().length>0))return mr(!1),t;const r=(0,o.A)((0,o.A)({},e),{},{id:e.id}),a=Math.max(sm.current,fo()),i=Math.max(lm.current,yo()),s=Date.now()-a<1e4,l=Date.now()-i<1e4,d=!0===(null===t||void 0===t?void 0:t.paymentEnabled),c=!1===e.paymentEnabled||void 0===e.paymentEnabled;
1(s||d&&c)&&(r.paymentEnabled=!0,void 0!==(null===t||void 0===t?void 0:t.paymentAmountCents)&&(r.paymentAmountCents=t.paymentAmountCents),void 0!==(null===t||void 0===t?void 0:t.paymentAmountFieldId)&&(r.paymentAmountFieldId=t.paymentAmountFieldId));const u=!0===(null===t||void 0===t?void 0:t.paymentSubscriptionEnabled),m=!1===e.paymentSubscriptionEnabled||void 0===e.paymentSubscriptionEnabled;return(l||u&&m)&&(r.paymentSubscriptionEnabled=!0,void 0!==(null===t||void 0===t?void 0:t.paymentSubscriptionAmountCents)&&(r.paymentSubscriptionAmountCents=t.paymentSubscriptionAmountCents),void 0!==(null===t||void 0===t?void 0:t.paymentSubscriptionProductName)&&(r.paymentSubscriptionProductName=t.paymentSubscriptionProductName),void 0!==(null===t||void 0===t?void 0:t.paymentSubscriptionInterval)&&(r.paymentSubscriptionInterval=t.paymentSubscriptionInterval)),void 0!==(null===t||void 0===t?void 0:t.paymentRevealAfterSignature)&&void 0===r.paymentRevealAfterSignature&&(r.paymentRevealAfterSignature=t.paymentRevealAfterSignature),void 0!==(null===t||void 0===t?void 0:t.paymentProductName)&&void 0===r.paymentProductName&&(r.paymentProductName=t.paymentProductName),void 0!==(null===t||void 0===t?void 0:t.paymentReminderEnabled)&&void 0===r.paymentReminderEnabled&&(r.paymentReminderEnabled=t.paymentReminderEnabled),r}),mr(!1)):((0,W.gg)("SKIPPING incomplete decrypted document"),ir(e=>(null===e||void 0===e?void 0:e.id)!==Ve?((0,W.gg)("\ud83e\uddf9 Clearing stale currentDoc - incomplete decrypted document"),null):e),mr(!1)):((0,W.gg)("SKIPPING document - ID mismatch or null:",{docId:null===e||void 0===e?void 0:e.id,currentPage:Ve,docIsNull:!e}),ir(e=>(null===e||void 0===e?void 0:e.id)!==Ve?((0,W.gg)("\ud83e\uddf9 Clearing stale currentDoc - document ID mismatch or null"),null):e),mr(!1))}).catch(e=>{console.error("Error loading document:",e),Ys.current.set(Ve,!0),ir(e=>(null===e||void 0===e?void 0:e.id)!==Ve?((0,W.gg)("\ud83e\uddf9 Clearing stale currentDoc - error loading document"),null):e),mr(!1)})):mr(!1)},[$h,Ve]);const Xh=Jh&&0!==Jh.length?Jh.map(e=>Pn.documents.find(t=>t.id===e.documentId)).filter(Boolean):[],ef=e=>{ir(null),window.innerWidth<1024&&Qe(!1),Je(e)},tf=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return(0,We.jsx)(Pa,{currentWorkspace:e,allDocuments:t,showFavorites:an,favoriteDocuments:Xh,favoritesLoading:qh,expandedCategories:Kt,toggleCategory:Qh,currentPage:Ve,onDocumentClick:ef,onReorder:n.onReorder,categoryOrder:n.categoryOrder,onCategoryReorder:n.onCategoryReorder})},nf=(0,i.useState)(!0),rf=(0,a.A)(nf,2),of=rf[0],af=rf[1],sf=(0,i.useState)({key:"",ready:!1}),lf=(0,a.A)(sf,2),df=lf[0],cf=lf[1],uf=(0,i.useMemo)(()=>[(null===Z||void 0===Z?void 0:Z.uid)||"no-user",zo,Lo||"no-workspace",jo||"no-workspaces",null!==Pn&&void 0!==Pn&&Pn.processed?"processed":"pending"].join(":"),[zo,null===Z||void 0===Z?void 0:Z.uid,Lo,null===Pn||void 0===Pn?void 0:Pn.processed,jo]);(0,i.useEffect)(()=>{af(!(null!==Pn&&void 0!==Pn&&Pn.processed))},[null===Pn||void 0===Pn?void 0:Pn.processed]),(0,i.useEffect)(()=>{if(cf({key:uf,ready:!1}),null===Pn||void 0===Pn||!Pn.processed)return;const e=window.setTimeout(()=>{cf({key:uf,ready:!0})},400);return()=>window.clearTimeout(e)},[uf,null===Pn||void 0===Pn?void 0:Pn.processed]);const mf=()=>{var e,t,n;const r="global"!==zo,a=0===(null===Or||void 0===Or?void 0:Or.length)&&(!Ne||!qo)&&!(null!==X&&void 0!==X&&X.isAnonymous)&&r,T=Boolean(Hr)&&0===(null===Or||void 0===Or?void 0:Or.length)&&!(null!==X&&void 0!==X&&X.isAnonymous)&&r&&qo&&!Ho,R=!1===(null===Z||void 0===Z?void 0:Z.emailVerified);if(T&&Z)return(0,We.jsxs)("div",{className:"space-y-6",children:[(0,We.jsxs)("div",{className:"pb-5 border-b border-gray-200",children:[(0,We.jsx)("h1",{className:"text-3xl font-bold text-gray-900",children:R?"Check your email to finish joining":"Finish joining your client workspace"}),(0,We.jsx)("p",{className:"text-gray-500 mt-2",children:R?"We found your client invite. Open the sign-in or verification link from Based in your email to continue.":"We found your client invite, but workspace access has not finished applying to this account yet."})]}),(0,We.jsxs)("div",{className:"max-w-xl rounded-lg border border-blue-100 bg-blue-50 p-5",children:[(0,We.jsx)("p",{className:"text-sm text-blue-900",children:R?"After you sign in from the email link, return here and we will retry joining your client organization.":"Click below to retry joining the client organization. This refreshes your account and applies the workspace access from the partner."}),xo&&(0,We.jsx)("p",{className:"mt-3 rounded-md border border-red-100 bg-red-50 px-3 py-2 text-sm text-red-700",children:xo}),(0,We.jsx)(St.A,{type:"button",className:"mt-4",loading:eo,onClick:Jo,children:R?"Resend email":"Finish joining"})]})]});const O=!0===(null===Pn||void 0===Pn?void 0:Pn.processed),F=r&&0===(null===Or||void 0===Or?void 0:Or.length)&&!(null!==X&&void 0!==X&&X.isAnonymous)&&!T&&!qo;if(of||!Z||!O||a||F)return(0,We.jsxs)("div",{className:"space-y-6",children:[(0,We.jsx)("div",{className:"pb-5 border-b border-gray-200",children:"global"===zo?(0,We.jsx)("h1",{className:"text-3xl font-bold text-gray-900",children:"Knowledge Base"}):(0,We.jsxs)("div",{className:"animate-pulse","aria-hidden":"true",children:[(0,We.jsxs)("div",{className:"flex items-center gap-3",children:[(0,We.jsx)("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-gray-200"}),(0,We.jsx)("div",{className:"h-9 bg-gray-200 rounded w-56 sm:w-72"})]}),(0,We.jsxs)("div",{className:"mt-4 space-y-2.5",children:[(0,We.jsx)("div",{className:"h-5 bg-gray-200 rounded w-full max-w-2xl"}),(0,We.jsx)("div",{className:"h-5 bg-gray-200 rounded w-4/5 max-w-xl"})]})]})}),(0,We.jsx)("div",{className:"grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3",children:Array.from({length:6}).map((e,t)=>(0,We.jsx)(wn,{},"loading-".concat(t)))})]});const L="global"===zo,_=Or.map(e=>e.id);let U;if(L)U=Pn.documents.filter(e=>{const t=Array.isArray(e.workspaceIds)&&e.workspaceIds.some(e=>_.includes(e)),n=e.userId===Z.uid;return t||n});else{const e=String(Lo);U=Pn.documents.filter(t=>{if(!Array.isArray(t.workspaceIds))return!1;const n=t.workspaceIds.some(n=>null===n||void 0===n?((0,W.gg)('\ud83d\udcdd Document "'.concat(t.title||t.fileName,'" has null workspace, treating as default')),"Default"===e):String(n)===e),r=Or.s
1ome(t=>t.id===e);return(0,W.gg)('\ud83d\udd0d Workspace filter for "'.concat(t.title||t.fileName,'":'),{workspaceIds:t.workspaceIds,currentWorkspaceId:e,hasValidWorkspace:n,workspaceExists:r,result:n&&r}),n&&r});const t=Array.from(new Map(U.map(e=>[e.id,e])).values());U=t,(0,W.gg)('\ud83d\udcca GRID VIEW - Documents for workspace "'.concat(e,'": ').concat(U.length," documents"));const n=U.map(e=>({id:e.id,title:(0,_e.Od)(e,"Untitled"),category:e.category,status:e.status}));(0,W.gg)("\ud83d\udccb GRID VIEW - Document list:",n),8!==U.length&&(0,W.gg)("\u26a0\ufe0f Document count mismatch: Expected ~8 documents, but found ".concat(U.length," for workspace ").concat(e))}const M=!L&&Lo?Or.find(e=>e.id===Lo):null,z=Ot(null===M||void 0===M?void 0:M.documentFolders),V=L?U:function(e,t,n){if(!Array.isArray(e))return[];if(null==t||""===t){const t=new Set(Ot(n).map(e=>e.id));return e.filter(e=>{const n=Ft(e);return null==n||!t.has(n)})}return e.filter(e=>Ft(e)===t)}(U,El,z),J=(0,io.c3)(V,fl),q=J.filter(e=>"processing"===e.status).length,K=df.key===uf&&df.ready,Q=0===U.length&&!K,Y=!Q&&!L&&null!=El&&0===J.length,$=!L&&null==El&&z.length>0&&"card"===dn,ee={};for(const o of z)ee[o.id]=0;for(const o of U){const e=Ft(o);e&&Object.prototype.hasOwnProperty.call(ee,e)&&(ee[e]+=1)}const te=async e=>{const t=L?"Knowledge Base":(null===M||void 0===M?void 0:M.name)||"Project";if(!e.trim()||e===t)return void ig(!1);const n=e.trim();try{const e=(0,B.doc)(G.db,"workspaces",Lo);await(0,B.mZ)(e,{name:n}),Fr(e=>e.map(e=>e.id===Lo?(0,o.A)((0,o.A)({},e),{},{name:n}):e)),bd(e=>e?(0,o.A)((0,o.A)({},e),{},{name:n}):e),window.dispatchEvent(new CustomEvent("workspacePropertyUpdated",{detail:{workspaceId:Lo,updates:{name:n}}})),ig(!1)}catch(r){console.error("Error updating workspace title:",r),ig(!1)}},ne=Ad[Lo]||(null===M||void 0===M?void 0:M.aiOverview)||null,re=Sd===Lo,oe=re?Pd:(0,lo.V)((null===ne||void 0===ne?void 0:ne.summary)||""),ae=Boolean(oe),ie=Boolean(ne&&"number"===typeof ne.docCount&&ne.docCount!==U.length),se=null===M||void 0===M?void 0:M.userRole,de=!!L||["admin","editor"].includes(se);(0,W.gg)("\u270d\ufe0f canEdit:",de);const ce=L?"Knowledge Base":(null===M||void 0===M?void 0:M.name)||"Project",me=L?"Browse all accessible documents":(null===M||void 0===M?void 0:M.description)||"",pe=(null===(e=z.find(e=>e.id===El))||void 0===e?void 0:e.name)||"Folder";return(0,We.jsxs)("div",{className:"brainMap"===dn?"flex flex-col gap-4":"space-y-6",children:[(0,We.jsxs)("div",{className:"relative flex justify-between items-center gap-3 min-w-0",children:[L?(0,We.jsx)("div",{className:"flex-1"}):(0,We.jsx)("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:El?(0,We.jsxs)("nav",{className:"flex items-center gap-1.5 min-w-0","aria-label":"Breadcrumb",children:[(0,We.jsx)("button",{type:"button",onClick:()=>Il(null),onDragOver:e=>{de&&ll&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move",pl("workspace-root"))},onDragLeave:()=>{pl(e=>"workspace-root"===e?null:e)},onDrop:e=>{if(!de||!ll)return;e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("docId")||ll;pl(null),dl(null),t&&Kp([t],null)},className:"text-xl sm:text-2xl font-bold truncate max-w-[40%] rounded px-1 -mx-1 transition-colors ".concat(ll&&"workspace-root"===ml?"text-brand bg-brand/10 ring-2 ring-brand":"text-gray-500 hover:text-brand"),title:ll?"Drop to move out of folder into All documents":"Back to ".concat(ce),children:ce}),(0,We.jsx)("span",{className:"text-xl sm:text-2xl font-bold text-gray-300 flex-shrink-0","aria-hidden":"true",children:"\u203a"}),nd?(0,We.jsxs)("form",{className:"flex items-center gap-1 min-w-0 flex-1",onSubmit:async e=>{e.preventDefault();const t=id.trim();if(t&&El)try{await $p(El,t),rd(!1)}catch(n){}},children:[(0,We.jsx)("input",{ref:cd,value:id,onChange:e=>sd(e.target.value),maxLength:60,className:"text-xl sm:text-2xl font-bold text-gray-900 bg-white border border-gray-300 rounded px-1.5 py-0.5 w-full min-w-0 focus:outline-none focus:ring-2 focus:ring-brand/30"}),(0,We.jsx)("button",{type:"submit",className:"p-1.5 text-brand hover:bg-brand/10 rounded flex-shrink-0",title:"Save",children:(0,We.jsx)(d.A,{className:"h-4 w-4"})}),(0,We.jsx)("button",{type:"button",onClick:()=>{rd(!1),sd(pe)},className:"p-1.5 text-gray-500 hover:bg-gray-100 rounded flex-shrink-0",title:"Cancel",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("h1",{className:"text-xl sm:text-2xl font-bold text-gray-900 truncate min-w-0",children:pe}),de&&(0,We.jsxs)("div",{className:"relative flex-shrink-0",ref:dd,children:[(0,We.jsx)("button",{type:"button",className:"p-1.5 rounded text-gray-400 hover:text-gray-700 hover:bg-gray-100",title:"Folder options","aria-label":"Options for folder ".concat(pe),onClick:()=>Xl(e=>!e),children:(0,We.jsx)(u.A,{className:"h-4 w-4"})}),$l&&(0,We.jsxs)("div",{className:"absolute left-0 top-full mt-1 z-50 w-44 bg-white border border-gray-200 rounded-md shadow-lg py-1",children:[(0,We.jsxs)("button",{type:"button",className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50",onClick:()=>{Xl(!1),sd(pe),rd(!0)},children:[(0,We.jsx)(m.A,{className:"h-3.5 w-3.5"}),"Rename"]}),(0,We.jsxs)("button",{type:"button",className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-red-600 hover:bg-red-50",onClick:()=>{Xl(!1),Xp(El)},children:[(0,We.jsx)(p.A,{className:"h-3.5 w-3.5"}),"Delete folder"]})]})]})]})]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)("button",{type:"button",onClick:()=>{de&&gg(!0)},className:"flex-shrink-0 flex items-center justify-center w-9 h-9 rounded-lg transition-colors duration-200 ".concat(de?"hover:bg-gray-100 cursor-pointer":"cursor-default"),title:de?"Click to change emoji":"",children:null!==M&&void 0!==M&&M.emoji?(0,We.jsx)("span",{className:"text-2xl leading-none",children:M.emoji}):(0,We.jsx)(g.A,{className:"w-6 h-6 text-gray-400"})}),ag?(0,We.jsx)("input",{type:"text",value:dg,onChange:e=>cg(e.target.value),onBlur:()=>te(dg),onKeyDown:e=>{"Enter"===e.key?te(dg):"Escape"===e.key&&ig(!1)},className:"text-xl sm:text-2xl font-bold text-gray-900 bg-transparent border-none outline-none focus:ring-2 focus:ring-blue-500 rounded px-1 w-full min-w-0",autoFocus:!0,onFocus:e=>e.target.select()}):(0,We.jsx)("h1",{className:"text-xl sm:text-2xl font-bold text-gray-900 rounded px-1 py-0.5 truncate min-w-0",onClick:()=>{de&&(cg(ce),ig(!0))},title:de?"Click to edit title":"",children:ce})]})}),!L&&de&&!zt(M,$g)&&(0,We.jsx)("div",{className:"flex items-center gap-3 flex-shrink-0",children:(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("button",{type:"button",onClick:()=>Cr("chatInsights"===Nr?"documents":"chatInsights"),className:"relative cursor-pointer px-3 py-2 rounded-md text-sm font-medium flex items-center gap-2 transition-colors ".concat("chatInsights"===Nr?"bg-blue-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"),"aria-pressed":"chatInsights"===Nr,children:[(0,We.jsx)(h.A,{className:"w-4 h-4 pointer-events-none","aria-hidden":!0}),(0,We.jsx)("span",{className:"pointer-events-none",children:"Inbox"}),"chatInsights"!==Nr&&rh>0&&(0,We.jsx)("span",{className:"absolute -top-1 -right-1 w-2.5 h-2.5 bg-red-500 rounded-full border-2 border-white pointer-events-none","aria-hidden":!0})]}),xd&&(0,We.jsxs)("div",{className:"relative",tabIndex:0,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||oc(!1)},children:[(0,We.jsxs)("div",{className:"flex items-stretch",children:[(0,We.jsxs)("button",{type:"button",onClick:Mc,className:"cursor-pointer flex items-center px-3 py-2 rounded-l-md text-sm font-medium transition-colors ".concat(Bd?"bg-blue-600 text-white":"bg-gray-100 text-gray-700 hover:bg-gray-200"),title:"Open AI Chat",children:[(0,We.jsx)(f.A,{className:"w-4 h-4 mr-2 pointer-events-none","aria-hidden":!0}),(0,We.jsx)("span",{className:"hidden sm:inline pointer-events-none",children:"AI Chat"})]}),(0,We.jsx)("button",{type:"button",onClick:()=>oc(e=>!e),className:"cursor-pointer flex items-center justify-center px-1.5 rounded-r-md text-sm font-medium transition-colors border-l ".concat(Bd?"bg-blue-600 text-white border-blue-500":"bg-gray-100 text-gray-700 hover:bg-gray-200 border-gray-200"),title:"Agent options",children:(0,We.jsx)(y.A,{className:"w-3.5 h-3.5 pointer-events-none transition-transform ".concat(rc?"rotate-180":""),"aria-hidden":!0})})]}),rc&&(0,We.jsxs)("div",{className:"absolute right-0 mt-2 w-64 bg-white border border-gray-200 rounded-lg shadow-lg z-50 py-1",children:[(0,We.jsxs)("button",{onClick:()=>{Mc(),oc(!1)},className:"w-full flex items-center gap-2 px-4 py-2 text-sm text-gray-700 hover:bg-gray-50",children:[(0,We.jsx)(f.A,{className:"w-4 h-4 text-blue-600"}),"Open AI Chat"]}),(0,We.jsx)("div",{className:"border-t border-gray-100 my-1"}),(0,We.jsx)("div",{className:"px-4 py-1.5 text-xs font-semibold text-gray-400 uppercase tracking-wide",children:"Exter
1nal Agents"}),0===sc.length&&(0,We.jsx)("div",{className:"px-4 py-2 text-sm text-gray-400 italic",children:"No agents created yet"}),sc.map(e=>(0,We.jsxs)("button",{onClick:()=>{pc(e),yc(!0),oc(!1)},className:"w-full flex items-center justify-between px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 group",children:[(0,We.jsx)("span",{className:"truncate",children:e.name}),(0,We.jsx)(v.A,{className:"w-3.5 h-3.5 text-gray-400 group-hover:text-blue-600 flex-shrink-0"})]},e.id)),(0,We.jsx)("div",{className:"border-t border-gray-100 my-1"}),(0,We.jsxs)("button",{onClick:()=>{pc(null),yc(!0),oc(!1)},className:"w-full flex items-center gap-2 px-4 py-2 text-sm text-blue-600 hover:bg-blue-50 font-medium",children:[(0,We.jsx)(x.A,{className:"w-4 h-4"}),"Create New Agent"]})]})]}),(0,We.jsxs)("div",{className:"relative",tabIndex:0,onBlur:e=>{if(!e.currentTarget.contains(e.relatedTarget)){const t=document.querySelector('[data-share-menu="true"]');if(t&&t.contains(e.relatedTarget))return;Mu(!1)}},children:[(0,We.jsxs)("button",{ref:Oc,type:"button",onClick:()=>{Mu(e=>{const t=!e;if(t&&An&&Oc.current){const e=Oc.current.getBoundingClientRect();Uc({left:e.left,top:e.bottom+8,right:window.innerWidth-e.right})}return t})},className:"inline-flex cursor-pointer items-center gap-2 px-3 py-2 border border-gray-300 shadow-sm rounded-md bg-white hover:bg-gray-50 transition-colors",title:"Share","aria-haspopup":"menu","aria-expanded":Uu,children:[(0,We.jsx)(l.A,{className:"h-4 w-4 text-gray-700 pointer-events-none","aria-hidden":!0}),(0,We.jsx)("span",{className:"text-sm font-medium text-gray-700 pointer-events-none",children:"Share"}),(0,We.jsx)(y.A,{className:"h-4 w-4 text-gray-400 pointer-events-none","aria-hidden":!0})]}),Uu&&(0,We.jsx)(We.Fragment,{children:An&&"undefined"!==typeof document?(0,s.createPortal)((0,We.jsxs)("div",{role:"menu","data-share-menu":"true",className:"fixed min-w-[320px] w-max max-w-[min(100vw-2rem,420px)] bg-white border border-gray-200 rounded-md shadow-lg z-[9999] overflow-hidden",style:{right:"".concat(_c.right,"px"),top:"".concat(_c.top,"px"),position:"fixed",isolation:"isolate"},onClick:e=>e.stopPropagation(),children:[(0,We.jsxs)("div",{className:"px-4 py-3 border-b border-gray-200",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(0,We.jsx)(l.A,{className:"h-4 w-4 text-gray-700"}),(0,We.jsx)("div",{className:"text-sm font-medium text-gray-900",children:"Share Links"})]}),(0,We.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"Create public links to share this workspace."})]}),0===ju.length?(0,We.jsx)("div",{className:"px-4 py-3 text-sm text-gray-400 italic",children:"No links created yet"}):(0,We.jsx)("div",{className:"max-h-[200px] overflow-y-auto",children:ju.map(e=>(0,We.jsxs)("button",{type:"button",onClick:()=>{qu(e),setTimeout(()=>Mu(!1),100)},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 group",children:[(0,We.jsxs)("div",{className:"flex-1 min-w-0 text-left",children:[(0,We.jsx)("div",{className:"truncate font-medium",children:e.linkLabel||"Shared Link"}),(0,We.jsx)("div",{className:"text-xs text-gray-400 truncate",children:Qu(e.createdAt)})]}),(0,We.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[e.isPublic?(0,We.jsx)(l.A,{className:"w-3.5 h-3.5 text-green-500"}):(0,We.jsx)(b.A,{className:"w-3.5 h-3.5 text-gray-400"}),(0,We.jsx)("span",{role:"button",tabIndex:0,onClick:t=>{t.stopPropagation(),Ku(e)},onKeyDown:t=>{"Enter"===t.key&&(t.stopPropagation(),Ku(e))},className:"p-1 rounded hover:bg-gray-200",title:"Copy link",children:Tu===e.id?(0,We.jsx)(d.A,{className:"w-3.5 h-3.5 text-green-500"}):(0,We.jsx)(w.A,{className:"w-3.5 h-3.5 text-gray-400 group-hover:text-gray-600"})})]})]},e.id))}),(0,We.jsx)("div",{className:"border-t border-gray-200",children:(0,We.jsxs)("button",{type:"button",role:"menuitem",onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),Hu(),setTimeout(()=>Mu(!1),100)},className:"w-full flex items-center gap-2 px-4 py-2.5 text-sm text-blue-600 hover:bg-gray-50",children:[(0,We.jsx)(x.A,{className:"h-4 w-4"}),"Create new link"]})}),(0,We.jsx)("div",{className:"border-t border-gray-200",children:Lo&&xd&&(0,We.jsxs)("button",{type:"button",role:"menuitem",onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),Ha(!0),setTimeout(()=>Mu(!1),100)},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50",title:"View workspace access",children:[(0,We.jsxs)("span",{className:"flex items-center gap-2",children:[(0,We.jsx)(k.A,{className:"h-4 w-4 text-gray-500"}
1),"Internal Access"]}),(0,We.jsx)(A.A,{className:"h-4 w-4 text-gray-300"})]})})]}),document.body):(0,We.jsxs)("div",{role:"menu","data-share-menu-desktop":"true",className:"absolute right-0 top-full mt-2 min-w-[320px] w-max max-w-[min(100vw-2rem,420px)] bg-white border border-gray-200 rounded-md shadow-lg z-50 overflow-hidden",children:[(0,We.jsxs)("div",{className:"px-4 py-3 border-b border-gray-200",children:[(0,We.jsxs)("div",{className:"flex items-center gap-2",children:[(0,We.jsx)(l.A,{className:"h-4 w-4 text-gray-700"}),(0,We.jsx)("div",{className:"text-sm font-medium text-gray-900",children:"Share Links"})]}),(0,We.jsx)("p",{className:"mt-1 text-xs text-gray-500",children:"Create public links to share this workspace."})]}),0===ju.length?(0,We.jsx)("div",{className:"px-4 py-3 text-sm text-gray-400 italic",children:"No links created yet"}):(0,We.jsx)("div",{className:"max-h-[200px] overflow-y-auto",children:ju.map(e=>(0,We.jsxs)("button",{type:"button",onClick:()=>{qu(e),setTimeout(()=>Mu(!1),100)},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 group",children:[(0,We.jsxs)("div",{className:"flex-1 min-w-0 text-left",children:[(0,We.jsx)("div",{className:"truncate font-medium",children:e.linkLabel||"Shared Link"}),(0,We.jsx)("div",{className:"text-xs text-gray-400 truncate",children:Qu(e.createdAt)})]}),(0,We.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0 ml-2",children:[e.isPublic?(0,We.jsx)(l.A,{className:"w-3.5 h-3.5 text-green-500"}):(0,We.jsx)(b.A,{className:"w-3.5 h-3.5 text-gray-400"}),(0,We.jsx)("span",{role:"button",tabIndex:0,onClick:t=>{t.stopPropagation(),Ku(e)},onKeyDown:t=>{"Enter"===t.key&&(t.stopPropagation(),Ku(e))},className:"p-1 rounded hover:bg-gray-200",title:"Copy link",children:Tu===e.id?(0,We.jsx)(d.A,{className:"w-3.5 h-3.5 text-green-500"}):(0,We.jsx)(w.A,{className:"w-3.5 h-3.5 text-gray-400 group-hover:text-gray-600"})})]})]},e.id))}),(0,We.jsx)("div",{className:"border-t border-gray-200",children:(0,We.jsxs)("button",{type:"button",role:"menuitem",onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),Hu(),setTimeout(()=>Mu(!1),100)},className:"w-full flex items-center gap-2 px-4 py-2.5 text-sm text-blue-600 hover:bg-gray-50",children:[(0,We.jsx)(x.A,{className:"h-4 w-4"}),"Create new link"]})}),(0,We.jsx)("div",{className:"border-t border-gray-200",children:Lo&&xd&&(0,We.jsxs)("button",{type:"button",role:"menuitem",onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),Ha(!0),setTimeout(()=>Mu(!1),100)},className:"w-full flex items-center justify-between px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50",title:"View workspace access",children:[(0,We.jsxs)("span",{className:"flex items-center gap-2",children:[(0,We.jsx)(k.A,{className:"h-4 w-4 text-gray-500"}),"Internal Access"]}),(0,We.jsx)(A.A,{className:"h-4 w-4 text-gray-300"})]})})]})})]})]})})]}),"chatInsights"===Nr?(0,We.jsx)("div",{className:"h-[calc(100vh-200px)] min-h-0 flex flex-col overflow-hidden",children:(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,We.jsx)(ci,{workspaceId:null===M||void 0===M?void 0:M.id,showUnreadIndicators:!zt(M,$g),unreadFormCount:(null===th||void 0===th?void 0:th[null===M||void 0===M?void 0:M.id])||0})})}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsxs)("div",{className:"pb-5 border-b border-gray-200",children:[L&&(0,We.jsx)("h1",{className:"text-3xl font-bold text-gray-900 rounded px-1 py-1",children:ce}),!El&&me?(0,We.jsx)("p",{className:"text-gray-500 ".concat(L?"mt-2":""),children:me}):null,!L&&!El&&!zt(M,$g)&&(ae||re)&&(0,We.jsxs)("div",{className:me?"mt-4":"",children:[(0,We.jsxs)("p",{className:"text-lg sm:text-xl text-on-surface leading-relaxed font-normal",children:[oe,re&&(0,We.jsx)("span",{className:"inline-block w-1.5 h-5 ml-0.5 -mb-0.5 bg-brand rounded-sm animate-pulse"})]}),!re&&de&&ie&&(0,We.jsxs)("button",{type:"button",onClick:()=>Ud(Lo),className:"mt-2 inline-flex items-center gap-1.5 text-xs font-medium text-brand hover:opacity-80",title:"Documents changed since this summary - update it",children:[(0,We.jsx)(j.A,{className:"w-3.5 h-3.5"}),"Update overview"]}),!re&&Fd&&(0,We.jsx)("p",{className:"text-xs text-red-500 mt-2",children:Fd})]}),!L&&(0,We.jsxs)("div",{className:"flex items-center justify-between gap-3 ".concat(!El&&(me||ae||re)?"mt-3":""),children:[(0,We.jsxs)("p",{className:"text-sm text-gray-400 min-w-0",children:[Q?"Loading documents...":El?"".concat(J.length," document").concat(1!==J.length?"s":""," in folder \xb7 ").concat(U.length," total"):"".concat(U.length," document").concat(1!==U.length?"s":""),!Q&&q>0&&" (".concat(q," processing)"),se&&" \u2022 ".concat(se)]}),(0,We.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0",children:[de&&!El&&(zl?(0,We.jsxs)("form",{className:"inline-flex items-center gap-1",onSubmit:async e=>{e.preventDefault();const t=Jl.trim();if(t&&!Kl){Ql(!0);try{await Zp(t)}catch(n){}finally{Ql(!1)}}},children:[(0,We.jsx)("input",{ref:ld,value:Jl,onChange:e=>ql(e.target.value),placeholder:"Folder name",disabled:Kl,maxLength:60,className:"w-36 px-2 py-1.5 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-brand/30"}),(0,We.jsx)("button",{type:"submit",disabled:Kl||!Jl.trim(),className:"p-1.5 text-brand hover:bg-brand/10 rounded disabled:opacity-50",title:"Create",children:(0,We.jsx)(d.A,{className:"h-4 w-4"})}),(0,We.jsx)("button",{type:"button",disabled:Kl,onClick:()=>{Bl(!1),ql("")},className:"p-1.5 text-gray-500 hover:bg-gray-100 rounded",title:"Cancel",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]}):(0,We.jsxs)("button",{type:"button",onClick:()=>Bl(!0),className:"inline-flex items-center gap-1.5 px-3 py-2 border border-dashed border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-600 bg-white hover:bg-gray-50 hover:border-gray-400",children:[(0,We.jsx)(N.A,{className:"h-4 w-4"}),"New folder"]})),(0,We.jsxs)("div",{className:"relative flex items-center",tabIndex:0,onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||vn(!1)},children:[(0,We.jsxs)("button",{type:"button",onClick:()=>vn(e=>!e),className:"inline-flex items-center px-3 py-2 border border-gray-300 shadow-sm text-sm leading-4 font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500","aria-haspopup":"menu","aria-expanded":yn,title:"Change view",children:[(()=>
1{const e="brainMap"===dn?"brainMap":"continuous"===dn?"continuous":pn,t="grid"===e?C.A:"list"===e?S.A:"brainMap"===e?E.A:I.A,n="grid"===e?"Grid":"list"===e?"List":"brainMap"===e?"Brain Map":"Continuous";return(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(t,{className:"mr-2 h-4 w-4"}),"View: ",n]})})(),(0,We.jsx)(y.A,{className:"ml-2 h-4 w-4 text-gray-400"})]}),yn&&(0,We.jsx)("div",{role:"menu",className:"absolute right-0 top-full mt-2 w-44 bg-white border border-gray-200 rounded-md shadow-lg z-50 overflow-hidden",children:[{key:"grid",label:"Grid",Icon:C.A,enabled:!0},{key:"list",label:"List",Icon:S.A,enabled:!0},{key:"continuous",label:"Continuous",Icon:I.A,enabled:de},{key:"brainMap",label:"Brain Map",Icon:E.A,enabled:!0}].filter(e=>e.enabled).map(e=>{let t=e.key,n=e.label,r=e.Icon;const o=("brainMap"===dn?"brainMap":"continuous"===dn?"continuous":pn)===t;return(0,We.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{"brainMap"===t?(Je(null),ir(null),cn("brainMap")):"continuous"===t?cn("continuous"):(cn("card"),gn(t)),vn(!1)},className:"w-full flex items-center justify-between px-3 py-2 text-sm hover:bg-gray-50 ".concat(o?"bg-blue-50 text-blue-700":"text-gray-700"),children:[(0,We.jsxs)("span",{className:"flex items-center",children:[(0,We.jsx)(r,{className:"mr-2 h-4 w-4 ".concat(o?"text-blue-600":"text-gray-400")}),n]}),o&&(0,We.jsx)(d.A,{className:"h-4 w-4 text-blue-600"})]},t)})})]})]})]})]}),el&&!L&&(0,We.jsxs)("div",{className:"bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg border border-blue-200",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between mb-4",children:[(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsx)(f.A,{className:"h-6 w-6 text-blue-600 mr-3"}),(0,We.jsxs)("div",{children:[(0,We.jsxs)("h3",{className:"text-lg font-semibold text-gray-900",children:[(null===M||void 0===M?void 0:M.name)||"Workspace"," AI Assistant"]}),(0,We.jsxs)("p",{className:"text-sm text-gray-600",children:["Ask questions about the ",null!==(t=null===ol||void 0===ol?void 0:ol.documentsCount)&&void 0!==t?t:U.length," documents in this workspace"]})]})]}),(0,We.jsx)("button",{onClick:()=>tl(!1),className:"text-gray-400 hover:text-gray-600",children:(0,We.jsx)(c.A,{className:"h-5 w-5"})})]}),ol&&(0,We.jsx)("div",{className:"mb-4 p-3 bg-green-50 border border-green-200 rounded-md",children:(0,We.jsxs)("div",{className:"flex items-center",children:[(0,We.jsx)("div",{className:"w-2 h-2 bg-green-500 rounded-full mr-2"}),(0,We.jsxs)("span",{className:"text-green-800 text-sm font-medium",children:["AI Agent is ready with access to ",null!==(n=null===ol||void 0===ol?void 0:ol.documentsCount)&&void 0!==n?n:U.length," documents"]})]})}),(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,We.jsx)(oi,{workspace:Or.find(e=>e.id===Lo),filteredDocuments:U,userProfile:le,activeDocumentId:yr,onAgentReady:e=>{var t;al({isReady:!0,agentId:e.agentId,documentsCount:null!==(t=e.documentsCount)&&void 0!==t?t:U.length})}})})]}),"card"===dn&&jl.size>0&&(0,We.jsxs)("div",{className:"flex flex-wrap items-center gap-3 py-2 px-3 rounded-lg bg-blue-50 border border-blue-200 mb-3",children:[(0,We.jsxs)("span",{className:"text-sm font-medium text-blue-900",children:[jl.size," selected"]}),(0,We.jsx)("button",{type:"button",onClick:Qo,disabled:za,className:"text-sm text-blue-700 hover:text-blue-900 underline disabled:opacity-50",children:"Clear"}),J.length>0&&jl.size<J.length&&(0,We.jsx)("button",{type:"button",onClick:()=>Ko(J),disabled:za,className:"text-sm text-blue-700 hover:text-blue-900 underline disabled:opacity-50",children:"Select all"}),(0,We.jsxs)("button",{type:"button",onClick:()=>Ra(!0),disabled:za,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded disabled:opacity-50",children:[(0,We.jsx)(p.A,{className:"h-4 w-4"}),"Delete"]}),!L&&Lo&&(0,We.jsxs)("button",{type:"button",onClick:()=>_a(!0),disabled:za,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded disabled:opacity-50",children:[(0,We.jsx)(p.A,{className:"h-4 w-4"}),"Remove from workspace"]}),!L&&de&&(0,We.jsxs)(We.Fragment,{children:[(El||Array.from(jl).some(e=>Ft(((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).find(t=>
1t.id===e))))&&(0,We.jsxs)("button",{type:"button",onClick:()=>{Kp(Array.from(jl),null)},disabled:za,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-gray-800 bg-white border border-gray-300 hover:bg-gray-50 rounded disabled:opacity-50",title:"Move selected documents out of their folder into All documents",children:[(0,We.jsx)(g.A,{className:"h-4 w-4"}),"Remove from folder"]}),z.length>0&&(0,We.jsxs)("div",{className:"relative",children:[(0,We.jsxs)("button",{type:"button",onClick:()=>gd(e=>!e),disabled:za,className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-blue-800 bg-white border border-blue-200 hover:bg-blue-50 rounded disabled:opacity-50",children:[(0,We.jsx)(g.A,{className:"h-4 w-4"}),"Move to folder",(0,We.jsx)(y.A,{className:"h-3.5 w-3.5"})]}),pd&&(0,We.jsxs)("div",{className:"absolute left-0 top-full mt-1 z-50 w-52 bg-white border border-gray-200 rounded-md shadow-lg py-1 max-h-56 overflow-y-auto",children:[(0,We.jsx)("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50",onClick:()=>{Kp(Array.from(jl),null)},children:"All documents"}),z.map(e=>(0,We.jsx)("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 truncate",onClick:()=>{Kp(Array.from(jl),e.id)},children:e.name},e.id))]})]})]})]}),Q?(0,We.jsx)(bn,{isLoading:!0,isGlobalView:L,canEdit:de}):Y?(0,We.jsxs)("div",{className:"rounded-lg border border-dashed border-gray-200 bg-gray-50/50 px-6 py-12 text-center",children:[(0,We.jsx)(g.A,{className:"h-8 w-8 text-gray-300 mx-auto mb-3"}),(0,We.jsx)("p",{className:"text-sm font-medium text-gray-700",children:"This folder is empty"}),(0,We.jsxs)("p",{className:"text-sm text-gray-500 mt-1",children:["Drag a document here from All documents, or select docs and use Move to folder. To remove docs from this folder, select them and choose Remove from folder \u2014 or drag onto ",ce,"."]}),(0,We.jsx)("button",{type:"button",onClick:()=>Il(null),className:"mt-4 text-sm text-brand hover:underline",children:"View all documents"})]}):0!==J.length||$?"brainMap"===dn?(0,We.jsx)("div",{className:"w-full",children:(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,We.jsx)(ui,{documents:Bp,categoryOrder:bl,workspaceId:(null===M||void 0===M?void 0:M.id)||("string"===typeof Lo?Lo:null===Lo||void 0===Lo?void 0:Lo.id),accessibleWorkspaceIds:(Or||[]).map(e=>String(e.id)),canEditCategory:de,categoryPresets:ps,peekDismissToken:Xd,onPeekOpenChange:e=>{Yd(!!e),e&&Wd(!1)},onCategoryChange:async(e,t)=>{await Cg(e,t||"Uncategorized")},onOpenDocument:e=>{ih(()=>{cn("card"),ir(null),Je(e)})}})})}):"continuous"===dn?(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,We.jsx)(ri,{doc:null,knowledgeBase:Pn,handleFavoriteToggle:Gh,isFavorite:Hh,onSwitchView:()=>zh("card"),currentViewKey:"continuous",onChangeViewKey:e=>{"brainMap"===e?(Je(null),ir(null),cn("brainMap")):"continuous"===e?zh("continuous"):(zh("card"),gn(e))},handleOpenShareModal:zu,currentWorkspace:Lo,onUpdateKnowledgeBase:pf,renderTOCInHeader:!0,tocContainerRef:Ec,embedded:!0})}):(0,We.jsxs)("div",{className:"rounded-lg border border-gray-200 bg-gray-50/50 ".concat("grid"===pn?"grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3 p-4":"space-y-2 p-3"),onDragOver:e=>{ll&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect="move")},onDrop:e=>{if(!de||!ll)return;e.preventDefault(),e.stopPropagation();const t=e.dataTransfer.getData("docId")||ll;if(!t)return dl(null),void pl(null);(0,W.gg)("\ud83c\udfaf Dropping on container (empty space), appending to end");const n=(fl||J.map(e=>e.id)).filter(e=>e!==t);n.push(t),yl(n),dl(null),pl(null),L?(0,B.mZ)((0,B.doc)(G.db,"users",Z.uid),{globalGridDocumentOrder:n,updatedAt:(0,B.O5)()}).catch(e=>{console.error("\u274c Failed to save global document order:",e)}):Lo&&(0,B.mZ)((0,B.doc)(G.db,"workspaces",Lo),{gridDocumentOrder:n,updatedAt:(0,B.O5)()}).catch(e=>{console.error("\u274c Failed to save workspace document order:",e)})},children:[$&&z.map(e=>{var t;const n=null!==(t=ee[e.id])&&void 0!==t?t:0,r=ll&&ml==="folder:".concat(e.id);return(0,We.jsx)(Ro,{folder:e,documentCount:n,layout:pn,isDropTarget:!!r,canEdit:de,onOpen:()=>Il(e.id),onRename:$p,onDelete:Xp,onDragOver:t=>{de&&ll&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect="move",pl("folder:".concat(e.id)))},onDragLeave:()=>{pl(t=>t==="folder:".concat(e.id)?null:t)},onDrop:t=>{if(!de||!ll)return;t.preventDefault(),t.stopPropagation();const n=t.dataTransfer.getData("docId")||ll;pl(null),dl(null),n&&Kp([n],e.id)}},"folder-card-".concat(e.id))}),J.map((e,t)=>{if("processing"===e.status)return(0,We.jsx)(wn,{},"processing-".concat(e.id));if(Ve===e.id&&(!ar||ar.id!==Ve))return(0,We.jsx)(wn,{},"loading-".concat(e.id));const n="image"===e.type||e.fileType&&e.fileType.startsWith("image/"),r=ll===e.id,o=ml===t&&ll!==e.id,a=ll?J.find(e=>e.id===ll):null;return"list"===pn?(0,We.jsxs)("div",{onDragOver:n=>{de&&ll&&ll!==e.id&&(n.preventDefault(),n.dataTransfer.dropEffect="move",pl(t))},onDragLeave:e=>{const t=e.currentTarget.getBoundingClientRect(),n=e.clientX,r=e.clientY;(n<t.left||n>t.right||r<t.top||r>t.bottom)&&pl(null)},onDrop:n=>{if(!de||!ll)return void(0,W.gg)("\u26a0\ufe0f Drop prevented: canEdit=",de,"draggedDocId=",ll);n.preventDefault(),n.stopPropagation();const r=n.dataTransfer.getData("docId")||ll;if((0,W.gg)("\ud83c\udfaf Drop event fired:",{droppedDocId:r,targetDocId:e.id,index:t,draggedDocId:ll}),!r)return(0,W.gg)("\u26a0\ufe0f No droppedDocId found"),dl(null),void pl(null);if(r===e.id)return(0,W.gg)("\u26a0\ufe0f Dropping on same document, resetting"),dl(null),void pl(null);(0,W.gg)("\ud83c\udfaf Dropping document:",r,"at index:",t,"target doc:",e.id);const o=fl||J.map(e=>e.id);(0,W.gg)("\ud83d\udccb Current order before update:",o);const a=o.filter(e=>e!==r),i=o.indexOf(e.id),s=i>=0?i:t;a.splice(s,0,r),(0,W.gg)("\ud83d\udccb New order after update:",a),yl(a),dl(null),pl(null),L?(0,B.mZ)((0,B.doc)(G.db,"users",Z.uid),{globalGridDocumentOrder:
1a,updatedAt:(0,B.O5)()}).then(async()=>{(0,W.gg)("\u2705 Global document order saved");const e=await(0,B.getDoc)((0,B.doc)(G.db,"users",Z.uid));if(e.exists()){const t=e.data();t.globalGridDocumentOrder&&yl(t.globalGridDocumentOrder)}}).catch(e=>{console.error("\u274c Failed to save global document order:",e),Ie.Ay.error("Failed to save document order")}):Lo&&(0,B.mZ)((0,B.doc)(G.db,"workspaces",Lo),{gridDocumentOrder:a,updatedAt:(0,B.O5)()}).then(async()=>{(0,W.gg)("\u2705 Workspace document order saved");const e=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",Lo));if(e.exists()){const t=e.data();t.gridDocumentOrder&&yl(t.gridDocumentOrder)}}).catch(e=>{console.error("\u274c Failed to save workspace document order:",e),Ie.Ay.error("Failed to save document order")}),dl(null),pl(null)},"data-doc-card":!0,className:"bg-white rounded-lg shadow-sm border transition-all duration-200 group relative select-none flex items-center gap-4 p-4 ".concat(de?"cursor-grab active:cursor-grabbing":"cursor-pointer"," ").concat(r?"opacity-20 scale-95 border-blue-500 border-2":o?"border-blue-500 border-2 shadow-lg bg-blue-50":ll&&ll!==e.id?"opacity-70":"border-gray-200 hover:shadow-md"," ").concat(jl.has(e.id)?"ring-2 ring-blue-500 border-blue-500":""),draggable:de,onDragStart:t=>{de&&yi(t,{docId:e.id,setDraggedDocId:dl,ghostRef:fd})},onDragEnd:e=>{de&&vi(e,{setDraggedDocId:dl,setDragOverIndex:pl,ghostRef:fd})},onClick:t=>{var n;const r=t.target,o=r.closest('[data-action="delete"]'),a=r.closest('[data-action="duplicate"]'),i=r.closest('[role="dialog"]')||r.closest(".fixed.inset-0"),s=r.closest('[data-action="select"]');o||a||i||s?(0,W.gg)("\ud83d\udeab Click ignored - came from delete button, duplicate button, modal, or select checkbox"):((0,W.gg)("\ud83d\uddb1\ufe0f Document clicked:",{docId:e.id,docTitle:(0,_e.Od)(e,"Untitled"),isRealId:!(null!==(n=e.id)&&void 0!==n&&n.startsWith("new_")),docObject:e}),ih(()=>{ir(null),window.innerWidth<1024&&Qe(!1),Je(e.id)}))},children:[de&&(0,We.jsx)("button",{type:"button","data-action":"select",onClick:t=>{t.stopPropagation(),Go(e.id)},className:"flex-shrink-0 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ".concat(jl.has(e.id)?"bg-blue-600 border-blue-600 text-white":"border-gray-300 hover:border-gray-400 bg-white"),"aria-label":jl.has(e.id)?"Deselect document":"Select document",children:jl.has(e.id)&&(0,We.jsx)(d.A,{className:"h-3 w-3"})}),(0,We.jsxs)("div",{className:"w-16 h-16 bg-gray-50 flex items-center justify-center flex-shrink-0 rounded-lg relative group/listcover overflow-hidden",children:[n?(0,We.jsx)("img",{src:e.previewUrl||"/api/files/".concat(e.fileName),alt:(0,_e.Od)(e,"Untitled Document"),className:"h-full w-full object-cover rounded-lg pointer-events-none select-none",style:{WebkitUserDrag:"none"},crossOrigin:"anonymous",draggable:!1}):e.coverImageUrl?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(oo.D,{src:(0,ro.a)(e.coverImageUrl,{width:160}),alt:e.title||"Cover image",className:"h-full w-full object-cover rounded-lg pointer-events-none select-none",style:(0,ao.Hw)(e.coverImagePosition,{WebkitUserDrag:"none"}),width:64,height:64,draggable:!1,fallback:(0,We.jsx)(Bn,{doc:e,className:"h-8 w-8"})}),(0,We.jsx)("button",{type:"button",onClick:t=>Wg(e,t),className:"absolute top-0.5 right-0.5 transition-opacity z-10 bg-black/50 hover:bg-black/70 text-white rounded p-1 cursor-pointer opacity-0 group-hover/listcover:opacity-100",title:"Change cover image",children:(0,We.jsx)(D.A,{className:"h-3 w-3"})})]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Bn,{doc:e,className:"h-8 w-8"}),de&&(0,We.jsx)("button",{type:"button",onClick:t=>Wg(e,t),disabled:Ig.has(e.id),className:"absolute top-0 right-0 z-10 rounded p-1 transition-opacity bg-black/50 hover:bg-black/70 text-white cursor-pointer ".concat(Ig.has(e.id)?"opacity-100":"opacity-0 group-hover/listcover:opacity-100"),title:"Add cover image",children:Ig.has(e.id)?(0,We.jsx)(P.A,{className:"h-3 w-3 animate-spin"}):(0,We.jsx)(D.A,{className:"h-3 w-3"})})]}),!n&&!e.coverImageUrl&&(0,We.jsx)("div",{className:"absolute bottom-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity",children:(0,We.jsx)("span",{className:"text-xs bg-white/90 backdrop-blur-sm px-1.5 py-0.5 rounded border border-gray-200 text-gray-600",children:(0,io.Hx)(e)})})]}),(0,We.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,We.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,We.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,We.jsx)("h3",{className:"text-sm font-medium text-gray-900 truncate",children:(0,_e.Od)(e,"Untitled Document")}),(0,We.jsxs)("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:["Uncategorized"!==(e.category||"Uncategorized")&&"General"!==e.category||!de?(0,We.jsx)("p",{className:"text-xs text-gray-500",children:e.category||"Uncategorized"}):(0,We.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),t.preventDefault(),Gg(e)},disabled:qg.has(e.id),className:"text-xs text-gray-500 hover:text-gray-700 hover:underline focus:outline-none focus:ring-0 disabled:opacity-50",title:"Fetch category",children:qg.has(e.id)?"\u2026":e.category||"Uncategorized"}),(0,We.jsx)(wi,{documentId:null===e||void 0===e?void 0:e.id,workspaceIds:(null===e||void 0===e?void 0:e.workspaceIds)||[],workspaceList:Or}),!0===(null===e||void 0===e?void 0:e.isTemplate)&&(0,We.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-800",title:"Used as a fillable template",children:"Template"}),es&&(0,We.jsx)(En,{documentId:null===e||void 0===e?void 0:e.id}),(()=>{const t=(0,Nn.AD)(e),n=t.visibleText,r=t.title;return n?(0,We.jsx)("p",{className:"text-xs text-gray-400",title:r||void 0,children:n}):null})()]})]}),de&&(0,We.jsxs)("div",{className:"flex items-center space-x-2 flex-shrink-0",children:[(0,We.jsx)("button",{onClick:async t=>{t.stopPropagation();try{await ng(e.id)}catch(n){}},onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"data-action":"duplicate",className:"p-1 text-gray-400 hover:text-blue-500 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 opacity-0 group-hover:opacity-100 transition-opacity",title:"Duplicate document",children:(0,We.jsx)(w.A,{className:"h-4 w-4"})}),(0,We.jsx)("button",{onClick:t=>{t.stopPropagation();const n=(0,_e.Od)(e,"Untitled Document");sa(""),ba(null),ra({doc:e,docTitle:n,isGlobalView:L,currentWorkspace:Lo,workspaceData:M}),Xo(!0)},onMouseDown:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),"data-action":"delete",className:"p-1 text-gray-400 hover:text-red-500 rounded focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-red-500 opacity-0 group-hover:opacity-100 transition-opacity",title:"Delete document",children:(0,We.jsx)(p.A,{className:"h-4 w-4"})})]})]}),(()=>{const t=Lt(e,z),n=e.workspaceIds&&Array.isArray(e.workspaceIds)&&Or?e.workspaceIds.filter(e=>null!==e&&void 0!==e).map(e=>{const t=Or.find(t=>
1t.id===e);return t?t.name:null}).filter(e=>null!==e):[];return t||0!==n.length?(0,We.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap mt-1",children:[t&&(0,We.jsxs)("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs font-medium bg-surface-muted text-on-surface border border-hairline",children:[(0,We.jsx)(g.A,{className:"h-3 w-3"}),t]}),n.map((e,t)=>(0,We.jsx)("span",{className:"inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700",children:e},t))]}):null})()]}),o&&ll&&(0,We.jsx)("div",{className:"absolute inset-0 bg-blue-100 bg-opacity-50 border-2 border-dashed border-blue-500 rounded-lg flex items-center justify-center z-20 pointer-events-none",children:(0,We.jsxs)("div",{className:"text-center",children:[(0,We.jsx)("div",{className:"text-sm font-semibold text-blue-700",children:"Drop here"}),(0,We.jsx)("div",{className:"text-xs text-blue-600 mt-1",children:(0,_e.Od)(a,"Document")})]})})]},e.id):(0,We.jsxs)("div",{onDragOver:n=>{de&&ll&&ll!==e.id&&(n.preventDefault(),n.dataTransfer.dropEffect="move",pl(t))},onDragLeave:e=>{const t=e.currentTarget.getBoundingClientRect(),n=e.clientX,r=e.clientY;(n<t.left||n>t.right||r<t.top||r>t.bottom)&&pl(null)},onDrop:n=>{if(!de||!ll)return void(0,W.gg)("\u26a0\ufe0f Drop prevented: canEdit=",de,"draggedDocId=",ll);n.preventDefault(),n.stopPropagation();const r=n.dataTransfer.getData("docId")||ll;if((0,W.gg)("\ud83c\udfaf Drop event fired (grid):",{droppedDocId:r,targetDocId:e.id,index:t,draggedDocId:ll}),!r)return(0,W.gg)("\u26a0\ufe0f No droppedDocId found"),dl(null),void pl(null);if(r===e.id)return(0,W.gg)("\u26a0\ufe0f Dropping on same document, resetting"),dl(null),void pl(null);(0,W.gg)("\ud83c\udfaf Dropping document:",r,"at index:",t,"target doc:",e.id);const o=fl||J.map(e=>e.id);(0,W.gg)("\ud83d\udccb Current order before update:",o);const a=o.filter(e=>e!==r),i=o.indexOf(e.id),s=i>=0?i:t;a.splice(s,0,r),(0,W.gg)("\ud83d\udccb New order after update:",a),yl(a),dl(null),pl(null),L?(0,B.mZ)((0,B.doc)(G.db,"users",Z.uid),{globalGridDocumentOrder:a,updatedAt:(0,B.O5)()}).then(async()=>{(0,W.gg)("\u2705 Global grid document order saved");const e=await(0,B.getDoc)((0,B.doc)(G.db,"users",Z.uid));if(e.exists()){const t=e.data();t.globalGridDocumentOrder&&yl(t.globalGridDocumentOrder)}}).catch(e=>{console.error("\u274c Failed to save global grid document order:",e),Ie.Ay.error("Failed to save document order")}):Lo&&(0,B.mZ)((0,B.doc)(G.db,"workspaces",Lo),{gridDocumentOrder:a,updatedAt:(0,B.O5)()}).then(async()=>{(0,W.gg)("\u2705 Workspace grid document order saved");const e=await(0,B.getDoc)((0,B.doc)(G.db,"workspaces",Lo));if(e.exists()){const t=e.data();t.gridDocumentOrder&&yl(t.gridDocumentOrder)}}).catch(e=>{console.error("\u274c Failed to save workspace grid document order:",e),Ie.Ay.error("Failed to save document order")}),dl(null),pl(null)},"data-doc-card":!0,className:"bg-white rounded-lg shadow-sm border transition-all duration-200 group relative select-none ".concat(de?"cursor-grab active:cursor-grabbing":"cursor-pointer"," ").concat(r?"opacity-20 scale-90 border-blue-500 border-2 ring-4 ring-blue-300 ring-opacity-70 blur-sm":o?"border-blue-500 border-2 shadow-2xl scale-[1.02] bg-blue-50 ring-2 ring-blue-300":ll&&ll!==e.id?"opacity-70":"border-gray-200 hover:shadow-md"," ").concat(jl.has(e.id)?"ring-2 ring-blue-500 border-blue-500":""),draggable:de,onDragStart:t=>{de&&yi(t,{docId:e.id,setDraggedDocId:dl,ghostRef:fd})},onDragEnd:e=>{de&&vi(e,{setDraggedDocId:dl,setDragOverIndex:pl,ghostRef:fd})},onClick:t=>{var n;const r=t.target,o=r.closest('[data-action="delete"]'),a=r.closest('[data-action="duplicate"]'),i=r.closest('[role="dialog"]')||r.closest(".fixed.inset-0"),s=r.closest('[data-action="select"]');o||a||i||s?(0,W.gg)("\ud83d\udeab Click ignored - came from delete button, duplicate button, modal, or select checkbox"):((0,W.gg)("\ud83d\uddb1\ufe0f Document clicked:",{docId:e.id,docTitle:(0,_e.Od)(e,"Untitled"),isRealId:!(null!==(n=e.id)&&void 0!==n&&n.startsWith("new_")),docObject:e}),ih(()=>{ir(null),window.innerWidth<1024&&Qe(!1),Je(e.id)}))},children:[de&&(0,We.jsx)("button",{type:"button","data-action":"select",onClick:t=>{t.stopPropagation(),Go(e.id)},className:"absolute top-2 left-2 z-10 w-5 h-5 rounded border-2 flex items-center justify-center transition-colors ".concat(jl.has(e.id)?"bg-blue-600 border-blue-600 text-white":"border-gray-300 hover:border-gray-400 bg-white opacity-0 group-hover:opacity-100"),"aria-label":jl.has(e.id)?"Deselect document":"Select document",children:jl.has(e.id)&&(0,We.jsx)(d.A,{className:"h-3 w-3"})}),(0,We.jsxs)("div",{className:"h-32 bg-gray-50 flex items-center justify-center relative group/cover rounded-t-lg overflow-hidden",children:[n?(0,We.jsx)("img",{src:e.previewUrl||"/api/files/".concat(e.fileName),alt:(0,_e.Od)(e,"Untitled Document"),className:"h-full w-full object-cover pointer-events-none select-none",style:{WebkitUserDrag:"none"},crossOrigin:"anonymous",draggable:!1}):e.coverImageUrl?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(oo.D,{src:(0,ro.a)(e.coverImageUrl,{width:480}),alt:e.title||"Cover image",className:"h-full w-full object-cover pointer-events-none select-none",style:(0,ao.Hw)(e.coverImagePosition,{WebkitUserDrag:"none"}),width:480,height:128,draggable:!1,fallback:(0,We.jsx)(Bn,{doc:e,className:"h-16 w-16"})}),(0,We.jsx)("button",{type:"button",onClick:t=>Wg(e,t),className:"absolute top-2 right-2 transition-opacity z-10 bg-black/50 hover:bg-black/70 text-white rounded-full p-1.5 cursor-pointer opacity-0 group-hover/cover:opacity-100",title:"Change cover image",children:(0,We.jsx)(D.A,{className:"h-3.5 w-3.5"})})]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(Bn,{doc:e,className:"h-16 w-16"}),de&&(0,We.jsx)("button",{type:"button",onClick:t=>Wg(e,t),disabled:Ig.has(e.id),className:"absolute top-2 right-2 z-10 rounded-full p-1.5 transition-opacity bg-black/50 hover:bg-black/70 text-white cursor-pointer ".concat(Ig.has(e.id)?"opacity-100":"opacity-0 group-hover/cover:opacity-100"),title:"Add cover image",children:Ig.has(e.id)?(0,We.jsx)(P.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,We.jsx)(D.A,{className:"h-3.5 w-3.5"})})]}),!n&&!e.coverImageUrl&&(0,We.jsx)("div",{className:"absolute bottom-2 right-2 opacity-0 group-hover/cover:opacity-100 transition-opacity",children:(0,We.jsx)("span",{className:"text-xs bg-white/90 backdrop-blur-sm px-2 py-1 rounded-full border border-gray-200 text-gray-600",children:(0,io.Hx)(e)})})]}),(0,We.jsx)(Tn,{doc:e,canEdit:de,isGlobalView:L,workspaceData:M,currentWorkspace:Lo,deleteDocument:H.Nn,removeDocumentFromWorkspace:H.vD,getKnowledgeBaseDocuments:H.gc,setKnowledgeBase:Rn,navigate:Fe,workspaceList:Or,documentSignaturesEnabled:es,documentLockEnabled:ts,onDuplicate:de?ng:void 0,organizationId:ue,onFetchCategory:Gg,fetchingCategoryDocIds:qg}),o&&ll&&(0,We.jsx)("div",{className:"absolute inset-0 bg-blue-100 bg-opacity-50 border-2 border-dashed border-blue-500 rounded-lg flex items-center justify-center z-20 pointer-events-none",children:(0,We.jsxs)("div",{className:"text-center",children:[(0,We.jsx)("div",{className:"text-sm font-semibold text-blue-700",children:"Drop here"}),(0,We.jsx)("div",{className:"text-xs text-blue-600 mt-1",children:(0,_e.Od)(a,"Document")})]})})]},e.id)})]}):(0,We.jsx)(bn,{isLoading:!1,isGlobalView:L,canEdit:de})]})]})},pf=async e=>{if((0,W.gg)("\ud83d\udd25 persistKnowledgeBase called with:",e),(0,W.gg)("\ud83d\uddc2\ufe0f selectedWorkspaceId:",Lo),(0,W.gg)("\ud83c\udf0d activeView:",zo),null===Z||void 0===Z||!Z.uid)return(0,W.gg)("\u274c No current user - not saving categoryOrder"),{success:!1,error:"No current user"};try{const t={categoryOrder:e.categoryOrder||[],documentOrder:e.documentOrder||{},documents:e.documents||[],updatedAt:Date.now()},n=JSON.parse(JSON.stringify(t,(e,t)=>void 0===t?null:t)),r=Lo;if((0,W.gg)("\ud83c\udfaf targetWorkspaceId:",r),"global"===zo)(0,W.gg)("\ud83d\udcbe Saving global categoryOrder and documentOrder to user preferences:",Z.uid),await(0,B.mZ)((0,B.doc)(G.db,"users",Z.uid),{globalCategoryOrder:n.categoryOrder,globalDocumentOrder:n.documentOrder,globalDocuments:n.documents,updatedAt:n.updatedAt}),(0,W.gg)("\u2705 Global categoryOrder and documentOrder updated successfully");else{if(!r)return(0,W.gg)("\u274c No valid save location found"),(0,W.gg)("\u274c targetWorkspaceId:",r,"activeView:",zo),{success:!1,error:"No valid save location"};(0,W.gg)("\ud83d\udcbe Saving categoryOrder and documentOrder to workspace:",r),await(0,B.mZ)((0,B.doc)(G.db,"workspaces",r),{categoryOrder:n.categoryOrder,documentOrder:n.documentOrder,documents:n.documents,updatedAt:n.updatedAt}),(0,W.gg)("\u2705 Workspace categoryOrder and documentOrder updated successfully")}return Rn(e=>(0,o.A)((0,o.A)({},e),{},{categoryOrder:n.categoryOrder,documentOrder:n.documentOrder,documents:n.documents,updatedAt:n.updatedAt})),(0,W.gg)("\u2705 Local state updated"),{success:!0}}catch(t){return console.error("\u274c Failed to update categoryOrder and documentOrder:",t),{success:!1,error:t.message}}},gf=e=>{const t=e.url||e.previewUrl||e.fileUrl||e.downloadUrl,n=(0,_e.Od)(e,"PDF");return(0,We.jsxs)("div",{className:"flex flex-col flex-1 min-h-0 w-full bg-white",children:[(0,We.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 border-b border-gray-200 px-4 sm:px-6 py-3 shrink-0",children:[(0,We.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,We.jsx)(ki,{docId:e.id,fileName:e.fileName,title:e.title,onRename:Ng}),(0,We.jsx)("div",{className:"mt-1.5 min-w-0",children:(0,We.jsx)(Ze.A,{metadataOnly:!0,showBackLink:!1,currentDoc:e,onCategoryChange:oh,categoryPresets:ps,onWorkspaceChange:jg,availableWorksp
1aces:(null===Or||void 0===Or?void 0:Or.map(e=>e.name))||[],workspaceList:Or,onCreateWorkspace:Zg})})]}),t?(0,We.jsx)("div",{className:"flex items-center gap-2 shrink-0",children:(0,We.jsxs)("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-blue-700 bg-blue-50 rounded-lg hover:bg-blue-100",children:[(0,We.jsx)(L.A,{className:"h-4 w-4","aria-hidden":!0}),"Open in new tab"]})}):null]}),(0,We.jsx)("div",{className:"flex-1 min-h-[320px] bg-gray-50 flex flex-col px-4 sm:px-6 py-4",children:t?(0,We.jsx)(Ya.yd,{downloadUrl:t,title:n,className:"w-full flex-1 min-h-[70vh] rounded-lg border border-gray-200 bg-white"}):(0,We.jsxs)("div",{role:"status","aria-live":"polite",className:"flex flex-1 min-h-[70vh] flex-col items-center justify-center gap-3 rounded-lg border border-gray-200 bg-white px-4",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-600 shrink-0","aria-hidden":!0}),(0,We.jsx)("p",{className:"text-sm text-gray-600 text-center",children:"Preparing PDF viewer\u2026"})]})})]})};function hf(e){if("string"===typeof e&&e.trim().startsWith("{"))try{return JSON.parse(e)}catch(t){return null}return null}if(Z){var ff,yf,vf,xf,bf,wf,kf,Af,jf,Nf,Cf,Sf,Ef,If;const e=e=>{var t,n,r,o,i,s,l,d;const c={};if([{path:"procedures",data:null===e||void 0===e?void 0:e.procedures},{path:"info.procedures",data:null===e||void 0===e||null===(t=e.info)||void 0===t?void 0:t.procedures},{path:"info.data_structure_and_organization.procedures",data:null===e||void 0===e||null===(n=e.info)||void 0===n||null===(r=n.data_structure_and_organization)||void 0===r?void 0:r.procedures},{path:"data_structure_and_organization.procedures",data:null===e||void 0===e||null===(o=e.data_structure_and_organization)||void 0===o?void 0:o.procedures}
1].forEach(e=>{e.path;let t=e.data;t&&"object"===typeof t&&!Array.isArray(t)&&Object.entries(t).forEach(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];Array.isArray(r)&&(c[n]=r)})}),null!==e&&void 0!==e&&null!==(i=e.data_structure_and_organization)&&void 0!==i&&null!==(s=i.application_process)&&void 0!==s&&s.steps&&(c["Application Process"]=e.data_structure_and_organization.application_process.steps),null!==e&&void 0!==e&&null!==(l=e.data_structure_and_organization)&&void 0!==l&&null!==(d=l.payment_management)&&void 0!==d&&d.details&&(c["Payment Management"]=e.data_structure_and_organization.payment_management.details),null!==e&&void 0!==e&&e.formattedContent&&"string"===typeof e.formattedContent)try{if(e.formattedContent.startsWith("{")){const t=hf(e.formattedContent);t.procedures&&"object"===typeof t.procedures&&Object.entries(t.procedures).forEach(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];Array.isArray(r)&&(c[n]=r)})}}catch(u){console.warn("Failed to parse formattedContent for procedures:",u)}return c},t=()=>{var t,n,r,i,s,l,d,c,u,m,p,g,h,f,y,v,x,b,w,k,A,j,N,C,S,E,I,L,U,M,z,B,V,J;if(dt.trim()&&yt)return(0,We.jsxs)("div",{className:"flex flex-col items-center justify-center py-12",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-500 mb-4"}),(0,We.jsx)("p",{className:"text-gray-500",children:"Searching..."})]});if(dt.trim()&&wt&&!yt)return pt&&pt.length>0?(0,We.jsx)(Do,{results:pt,breadcrumbLabel:Ve?(0,_e.Od)(ar,"Current document"):"All documents",onBreadcrumbClick:qt,onResultClick:e=>{ih(()=>{const t=pt.find(t=>{var n;return(null===t||void 0===t||null===(n=t.document)||void 0===n?void 0:n.id)===e});Di(null===t||void 0===t?void 0:t.document),ir(null),Je(e),qt()})}}):(0,We.jsxs)("div",{className:"flex flex-col items-center justify-center py-12",children:[(0,We.jsxs)("nav",{"aria-label":"Breadcrumb",className:"mb-3 text-sm text-gray-500 flex items-center gap-2",children:[(0,We.jsx)("button",{type:"button",onClick:qt,className:"text-gray-600 hover:text-gray-900 hover:underline",children:Ve?(0,_e.Od)(ar,"Current document"):"All documents"}),(0,We.jsx)("span",{className:"text-gray-300",children:"/"}),(0,We.jsx)("span",{className:"text-gray-700",children:"Search Results"})]}),(0,We.jsx)(_.A,{className:"h-12 w-12 text-gray-400 mb-4"}),(0,We.jsx)("h2",{className:"text-xl font-semibold text-gray-900 mb-2",children:"No results found"}),(0,We.jsx)("p",{className:"text-gray-500",children:"Try different search terms or check your spelling."}),(0,We.jsx)("button",{onClick:()=>{qt()},className:"mt-4 text-blue-600 hover:text-blue-700 text-sm font-medium",children:"Clear search"})]});if(!Ve)return(0,W.gg)("\ud83d\udcc4 currentPage is null, rendering grid view"),an?(()=>{const e="global"===zo,t=!e&&Lo?null===Or||void 0===Or?void 0:Or.find(e=>e.id===Lo):null,n=!!e||["admin","editor"].includes(null===t||void 0===t?void 0:t.userRole);return(0,We.jsxs)("div",{className:"pb-5 mb-6",children:[(0,We.jsx)("h1",{className:"text-3xl font-bold text-gray-900",children:"Favorites"}),(0,We.jsx)("p",{className:"text-gray-500 mt-2",children:"Your favorited documents"}),(0,We.jsx)("div",{className:"mt-6 grid gap-4 grid-cols-1 md:grid-cols-2 lg:grid-cols-3",children:0===Xh.length?(0,We.jsxs)("div",{className:"col-span-full text-center py-10",children:[(0,We.jsx)(T.A,{className:"h-10 w-10 text-gray-300 mx-auto mb-4"}),(0,We.jsx)("p",{className:"text-gray-500",children:"No favorites yet"}),(0,We.jsx)("p",{className:"text-gray-400 text-sm mt-1",children:"Click the heart icon on any document to add it to your favorites"})]}):Xh.map(e=>(0,We.jsxs)("div",{className:"bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden",children:[(0,We.jsx)("div",{className:"h-32 bg-gray-100 flex items-center justify-center cursor-pointer relative group/favcover overflow-hidden",onClick:()=>{ir(null),Je(e.id)},children:"image"===e.type||e.fileType&&e.fileType.startsWith("image/")?(0,We.jsx)("img",{src:e.previewUrl||"/api/files/".concat(e.fileName),alt:(0,_e.Od)(e,"Untitled Document"),className:"h-full w-full object-cover",crossOrigin:"anonymous"}):e.coverImageUrl?(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(oo.D,{src:(0,ro.a)(e.coverImageUrl,{width:480}),alt:e.title||"Cover image",className:"h-full w-full object-cover",style:(0,ao.Hw)(e.coverImagePosition),width:480,height:128,fallback:(0,We.jsx)(R.A,{className:"h-12 w-12 text-gray-400"})}),(0,We.jsx)("button",{type:"button",onClick:t=>Wg(e,t),className:"absolute top-2 right-2 transition-opacity z-10 bg-black/50 hover:bg-black/70 text-white rounded-full p-1.5 cursor-pointer opacity-0 group-hover/favcover:opacity-100",title:"Change cover image",children:(0,We.jsx)(D.A,{className:"h-3.5 w-3.5"})})]}):(0,We.jsxs)(We.Fragment,{children:[(0,We.jsx)(R.A,{className:"h-12 w-12 text-gray-400"}),n&&(0,We.jsx)("button",{type:"button",onClick:t=>Wg(e,t),disabled:Ig.has(e.id),className:"absolute top-2 right-2 z-10 rounded-full p-1.5 transition-opacity bg-black/50 hover:bg-black/70 text-white cursor-pointer ".concat(Ig.has(e.id)?"opacity-100":"opacity-0 group-hover/favcover:opacity-100"),title:"Add cover image",children:Ig.has(e.id)?(0,We.jsx)(P.A,{className:"h-3.5 w-3.5 animate-spin"}):(0,We.jsx)(D.A,{className:"h-3.5 w-3.5"})})]})}),(0,We.jsxs)("div",{className:"p-4",children:[(0,We.jsxs)("div",{className:"flex items-center justify-between",children:[(0,We.jsx)("h3",{className:"text-sm font-medium text-gray-900 truncate cursor-pointer",onClick:()=>{ir(null),Je(e.id)},children:(0,_e.Od)(e,"Title")}),(0,We.jsx)("button",{onClick:()=>Gh(e),className:"text-red-500 hover:text-red-600",children:(0,We.jsx)(O.A,{className:"h-4 w-4 fill-current"})})]}),"Uncategorized"!==(e.category||"Uncategorized")&&"General"!==e.category||!n?(0,We.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:e.category||"Uncategorized"}):(0,We.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),t.preventDefault(),Gg(e)},disabled:qg.has(e.id),className:"text-xs text-gray-500 mt-1 hover:text-gray-700 hover:underline focus:outline-none focus:ring-0 disabled:opacity-50 block",title:"Fetch category",children:qg.has(e.id)?"\u2026":e.category||"Uncategorized"})]})]},e.id))})]})})():mf();const q=ar&&(ar.editorJson||"pdf"===ar.viewerMode||(0,oe.z7)(ar)),K=(null===ar||void 0===ar?void 0:ar.id)===Ve,Q=An?!ar||!q&&ur:!ar||!K&&!q||ur&&!q;if(An&&Q&&ar&&(0,W.v4)("\ud83d\udea8 MOBILE: Showing loading screen despite having currentDoc",{currentPage:Ve,currentDocId:null===ar||void 0===ar?void 0:ar.id,hasValidContent:q,idMatches:K,documentLoading:ur,shouldShowLoading:Q}),Q)return ur||ar?(0,We.jsxs)("div",{className:"flex flex-col items-center justify-center py-12 min-h-screen bg-white",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-500 mb-4"}),(0,We.jsx)("p",{className:"text-gray-500",children:"Loading document..."})]}):(0,We.jsxs)("div",{className:"flex flex-col items-center justify-center py-12 min-h-screen bg-white",children:[(0,We.jsx)("p",{className:"text-gray-800 font-medium mb-2",children:"Couldn't open this document"}),(0,We.jsx)("p",{className:"text-gray-500 text-sm mb-4 text-center max-w-sm",children:"It may be in another workspace, or you may 
1not have access."}),(0,We.jsx)("button",{type:"button",className:"text-blue-600 hover:text-blue-700 text-sm font-medium",onClick:()=>{Je(null),ir(null)},children:"Back to documents"})]});(0,W.gg)("Profile data:",le),(0,W.gg)("Firebase available:",G.j2);const Y=G.j2.currentUser;if((0,W.gg)("current user data:",Y),Y.getIdToken().then(e=>{(0,W.gg)("Auth Token:",e)}),Array.from(document.scripts).forEach(e=>{e.src.includes("firebase")&&(0,W.gg)("Firebase script:",e.src)}),!ar||"object"!==typeof ar)return console.warn("CurrentDoc is not available or not an object:",ar),(0,We.jsx)("div",{children:"Loading document..."});if((0,W.gg)("Current document in renderContent:",ar),(0,W.gg)("Document procedures raw (root):",null===ar||void 0===ar?void 0:ar.procedures),(0,W.gg)("Document procedures raw (info):",null===ar||void 0===ar||null===(t=ar.info)||void 0===t?void 0:t.procedures),(0,W.gg)("Document encryption status:",{hasEncryptedResult:Boolean(null===ar||void 0===ar?void 0:ar.encryptedResult),isEncrypted:null===ar||void 0===ar?void 0:ar.isEncrypted,isDecrypted:null===ar||void 0===ar?void 0:ar._isDecrypted,hasTextContent:Boolean(null===ar||void 0===ar?void 0:ar.textContent),textContentPreview:null===ar||void 0===ar||null===(n=ar.textContent)||void 0===n?void 0:n.substring(0,100),hasFormattedContent:Boolean(null===ar||void 0===ar?void 0:ar.formattedContent),formattedContentPreview:"string"===typeof(null===ar||void 0===ar?void 0:ar.formattedContent)?ar.formattedContent.substring(0,100):"Not a string",allKeys:Object.keys(ar||{})}),(0,W.gg)("\ud83d\udd0d Contact Data Debug:",{documentId:null===ar||void 0===ar?void 0:ar.id,title:null===ar||void 0===ar?void 0:ar.title,hasContactData:Boolean(null===ar||void 0===ar||null===(r=ar.info)||void 0===r?void 0:r.structured_data),contactDataKeys:null!==ar&&void 0!==ar&&null!==(i=ar.info)&&void 0!==i&&i.structured_data?Object.keys(ar.info.structured_data):null,contactDataMembers:(null===ar||void 0===ar||null===(s=ar.info)||void 0===s||null===(l=s.structured_data)||void 0===l||null===(d=l.members)||void 0===d?void 0:d.length)||0,contactDataVisitors:(null===ar||void 0===ar||null===(c=ar.info)||void 0===c||null===(u=c.structured_data)||void 0===u||null===(m=u.visitors)||void 0===m?void 0:m.length)||0,hasRootMembers:Boolean(null===ar||void 0===ar||null===(p=ar.info)||void 0===p?void 0:p.members),hasRootVisitors:Boolean(null===ar||void 0===ar||null===(g=ar.info)||void 0===g?void 0:g.visitors),allDocumentKeys:Object.keys(ar||{}),keyValueSample:Object.entries(ar||{}).slice(0,10).map(e=>{let t=(0,a.A)(e,2),n=t[0],r=t[1];return{key:n,type:typeof r,isArray:Array.isArray(r),length:Array.isArray(r)||"string"===typeof r?r.length:"N/A",sample:"string"===typeof r?r.substring(0,50)+"...":Array.isArray(r)?"Array(".concat(r.length,")"):"object"===typeof r?"Object(".concat(Object.keys(r||{}).length," keys)"):String(r)}})}),(0,W.gg)("\ud83d\udd0d Contact Display Condition Check:",{hasContactData:Boolean(null===(h=ar.info)||void 0===h?void 0:h.structured_data),hasStructuredMembers:Boolean(null===(f=ar.info)||void 0===f||null===(y=f.structured_data)||void 0===y?void 0:y.members),hasStructuredVisitors:Boolean(null===(v=ar.info)||void 0===v||null===(x=v.structured_data)||void 0===x?void 0:x.visitors),shouldShowContactSection:Boolean((null===(b=ar.info)||void 0===b?void 0:b.structured_data)||(null===(w=ar.info)||void 0===w||null===(k=w.structured_data)||void 0===k?void 0:k.members)||(null===(A=ar.info)||void 0===A||null===(j=A.structured_data)||void 0===j?void 0:j.visitors))}),ar&&ar.isEncrypted&&ar.encryptedResult&&!ar._isDecrypted){if(hr.has(ar.id)){const e="dual"!==ar.encryptionMethod||!ar.workspaceEncryptedResults;return(0,We.jsxs)("div",{className:"flex flex-col items-center justify-center p-12 text-center max-w-lg mx-auto",children:[(0,We.jsx)("div",{className:"text-4xl mb-4",children:"\ud83d\udd12"}),(0,We.jsx)("h3",{className:"text-lg font-semibold text-gray-800 dark:text-gray-200 mb-2",children:"Unable to decrypt this document"}),(0,We.jsx)("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e?"This document uses an older encryption format. The document owner needs to open and save it once to enable access for workspace members.":"This document was encrypted with a key you don't have access to. Please contact the document owner for assistance."})]})}console.warn("Document needs decryption - reloading...");const e=async()=>{try{var e;const t=null===Pn||void 0===Pn||null===(e=Pn.documents)||void 0===e?void 0:e.find(e=>e.id===ar.id),n=(null===Or||void 0===Or?void 0:Or.map(e=>String(e.id)))||[],r=await(0,H.YE)(ar.id,n);r&&r._isDecrypted&&t?((0,W.gg)("\ud83d\udd04 reloadWithDecryption preserving category:",{originalCategory:t.category,decryptedCategory:r.category,willUse:t.category||r.category}),Rn(e=>(0,o.A)((0,o.A)({},e),{},{documents:e.documents.map(e=>e.id===ar.id?(0,o.A)((0,o.A)({},r),{},{category:t.category||r.category||"",workspace:t.workspace||r.workspace||"Default",workspaceIds:t.workspaceIds||r.workspaceIds||[],_isDecrypted:!0}):e)}))):fr(e=>new Set(e).add(ar.id))}catch(t){console.error("Error decrypting document:",t),fr(e=>new Set(e).add(ar.id))}};if(e(),null!==ar&&void 0!==ar&&ar.encryptedResult&&!0!==(null===ar||void 0===ar?void 0:ar.isDecrypted))return(0,We.jsxs)("div",{className:"flex items-center justify-center p-8",children:[(0,We.jsx)(Se.y$,{size:"md",className:"text-blue-500"}),(0,We.jsx)("span",{className:"ml-3 text-gray-600",children:"Decrypting document..."})]})}if(null!==ar&&void 0!==ar&&ar._decryptionFailed){const e="dual"!==ar.encryptionMethod||!ar.workspaceEncryptedResults;return(0,We.jsxs)("div",{className:"flex flex-col items-center justify-center p-12 text-center max-w-lg mx-auto",children:[(0,We.jsx)("div",{className:"text-4xl mb-4",children:"\ud83d\udd12"}),(0,We.jsx)("h3",{className:"text-lg font-semibold text-gray-800 dark:text-gray-200 mb-2",children:"Unable to decrypt this document"}),(0,We.jsx)("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:e?"This document uses an older encryption format. The document owner needs to open and save it once to enable access for workspace members.":"This document was encrypted with a key you don't have access to. Please contact the document owner for assistance."})]})}if(!ar||"object"!==typeof ar)return console.warn("CurrentDoc is not available or not an object:",ar),(0,We.jsx)("div",{children:"Loading document..."});const Z={title:(0,_e.Od)(ar,"Untitled Document"),category:ar.category||"Uncategorized",subcategory:ar.subcategory||"",keyPoints:(e=>{if(ar.keyPoints&&Array.isArray(ar.keyPoints))return ar.keyPoints;if(null!==(e=ar.info)&&void 0!==e&&e.keyPoints&&Array.isArray(ar.info.keyPoints))return ar.info.keyPoints;try{if(null!==ar&&void 0!==ar&&ar.formattedContent&&"string"===typeof ar.formattedContent){const e=hf(ar.formattedContent);if(null!==e&&void 0!==e&&e.keyPoints&&Array.isArray(e.keyPoints))return e.keyPoints}}catch(t){console.error("Error parsing formattedContent for keyPoints:",t)}return[]})(),summary:(e=>{if(ar.summary&&"string"===typeof ar.summary)return ar.summary;if(null!==(e=ar.info)&&void 0!==e&&e.summary&&"string"===typeof ar.info.summary)return ar.info.summary;try{if(null!==ar&&void 0!==ar&&ar.formattedContent&&"string"===typeof ar.formattedContent){const e=hf(ar.formattedContent);if(null!==e&&void 0!==e&&e.summary&&"string"===typeof e.summary)return e.summary}}catch(t){console.error("Error parsing formattedContent for summary:",t)}return""})(),procedures:((t,n,r,o)=>{const a=e(ar);if(a&&"object"===typeof a&&Object.keys(a).length>0)return(0,W.gg)("\ud83d\udccb Found procedures via getAllProcedures:",a),a;try{if(null!==ar&&void 0!==ar&&ar.formattedContent&&"string"===typeof ar.formattedContent){const e=hf(ar.formattedContent);if(null!==e&&void 0!==e&&e.procedures&&"object"===typeof e.procedures&&Object.keys(e.procedures).length>0)return(0,W.gg)("\ud83d\udccb Found procedures in formattedContent:",e.procedures),e.procedures}}catch(i){console.error("Error parsing formattedContent for procedures:",i)}return((null===ar||void 0===ar||null===(t=ar.title)||void 0===t?void 0:t.toLowerCase().includes("proposal"))||(null===ar||void 0===ar||null===(n=ar.textContent)||void 0===n?void 0:n.toLowerCase().includes("proposal"))||(null===ar||void 0===ar||null===(r=ar.fileName)||void 0===r?void 0:r.toLowerCase().includes("proposal")))&&null!==ar&&void 0!==ar&&null!==(o=ar.textContent)&&void 0!==o&&o.includes("SCOPE")?((0,W.gg)("\ud83d\udccb Creating Scope of Work for proposal document"),{"Scope of Work":["Step 1: Film, edit, and produce YouTube videos that are educational, informative, and entertaining related to real estate and Alexandra Valencia's experiences","Step 2: Create long-form YouTube videos featuring real estate content and property tours","Step 3: Cut down long-form videos into smaller quick bits for platforms like Instagram and TikTok","Step 4: Develop real estate tour content where Alexandra provides valuable information about homes, buyer tips, and key questions to ask"]}):((0,W.gg)("\ud83d\udccb No procedures found in document"),{})})(),extractedPricing:(()=>
1{if(null!==ar&&void 0!==ar&&ar.extractedPricing&&Array.isArray(ar.extractedPricing))return ar.extractedPricing;try{if(null!==ar&&void 0!==ar&&ar.formattedContent&&"string"===typeof ar.formattedContent){const e=hf(ar.formattedContent);if(null!==e&&void 0!==e&&e.extractedPricing&&Array.isArray(e.extractedPricing))return e.extractedPricing}}catch(e){console.error("Error parsing formattedContent for pricing:",e)}return[]})(),salesPitch:(()=>{if(null!==ar&&void 0!==ar&&ar.salesPitch&&"string"===typeof ar.salesPitch)return ar.salesPitch;try{if(null!==ar&&void 0!==ar&&ar.formattedContent&&"string"===typeof ar.formattedContent){const e=hf(ar.formattedContent);if(null!==e&&void 0!==e&&e.salesPitch&&"string"===typeof e.salesPitch)return e.salesPitch}}catch(e){console.error("Error parsing formattedContent for sales pitch:",e)}return""})(),relatedTopics:(e=>{if(null!==ar&&void 0!==ar&&ar.relatedTopics&&Array.isArray(ar.relatedTopics))return ar.relatedTopics;if(null!==ar&&void 0!==ar&&null!==(e=ar.info)&&void 0!==e&&e.relatedTopics&&Array.isArray(ar.info.relatedTopics))return ar.info.relatedTopics;try{if(null!==ar&&void 0!==ar&&ar.formattedContent&&"string"===typeof ar.formattedContent){const e=hf(ar.formattedContent);if(null!==e&&void 0!==e&&e.relatedTopics&&Array.isArray(e.relatedTopics))return e.relatedTopics}}catch(t){console.error("Error parsing formattedContent for related topics:",t)}return[]})(),sectionLabels:ar.sectionLabels||{summary:"Summary",keyPoints:"Key Points",relatedTopics:"Related Topics"}};(0,W.gg)("\ud83d\udd0d Document Display Debug:",{documentId:null===ar||void 0===ar?void 0:ar.id,hasKeyPoints:Boolean(null===(N=Z.keyPoints)||void 0===N?void 0:N.length),keyPointsCount:(null===(C=Z.keyPoints)||void 0===C?void 0:C.length)||0,hasSummary:Boolean(Z.summary),summaryLength:(null===(S=Z.summary)||void 0===S?void 0:S.length)||0,hasFormattedContent:Boolean(null===ar||void 0===ar?void 0:ar.formattedContent),formattedContentType:typeof(null===ar||void 0===ar?void 0:ar.formattedContent),documentKeys:Object.keys(ar||{}),infoKeys:null!==ar&&void 0!==ar&&ar.info?Object.keys(ar.info):[],context:"renderContent function"}),(0,W.gg)("\ud83d\udd0d Enhanced Procedures Debug:",{editField:Zn,editValue:qn,editValueLength:null===qn||void 0===qn?void 0:qn.length,currentPage:Ve,hasCurrentDoc:!!ar,structuredDataSummary:null===(E=Z.summary)||void 0===E?void 0:E.substring(0,50),procedureKeys:Object.keys(Z.procedures||{}),proceduresCount:Object.keys(Z.procedures||{}).length,proceduresData:Z.procedures,rawProcedureLocations:{"root.procedures":!(null===ar||void 0===ar||!ar.procedures),"info.procedures":!(null===ar||void 0===ar||null===(I=ar.info)||void 0===I||!I.procedures),"info.data_structure_and_organization.procedures":!(null===ar||void 0===ar||null===(L=ar.info)||void 0===L||null===(U=L.data_structure_and_organization)||void 0===U||!U.procedures),"data_structure_and_organization.procedures":!(null===ar||void 0===ar||null===(M=ar.data_structure_and_organization)||void 0===M||!M.procedures),"data_structure_and_organization.application_process":!(null===ar||void 0===ar||null===(z=ar.data_structure_and_organization)||void 0===z||!z.application_process),"data_structure_and_organization.payment_management":!(null===ar||void 0===ar||null===(B=ar.data_structure_and_organization)||void 0===B||!B.payment_management)}});return"image"===ar.type||ar.fileType&&ar.fileType.startsWith("image/")?(e=>{var t,n,r;const o=e.previewUrl||e.url||"/api/files/".concat(e.fileName);return(0,We.jsxs)("div",{className:"mb-6",children:[(0,We.jsxs)("div",{className:"pb-5 border-b border-gray-200 mb-6 flex justify-between items-center",children:[(0,We.jsxs)("div",{children:[(0,We.jsx)("h1",{className:"text-3xl font-bold text-gray-900",children:e.title||(null===(t=e.info)||void 0===t?void 0:t.title)||e.fileName||"Image Details"}),(0,We.jsxs)("p",{className:"text-gray-500 mt-2",children:[e.category||"Uncategorized",e.subcategory]})]}),(0,We.jsxs)("div",{className:"flex items-center space-x-2",children:[(0,We.jsx)("button",{onClick:()=>Gh(e),className:"p-2 rounded-full ".concat(Hh(e.id)?"text-red-500 hover:text-red-600":"text-gray-400 hover:text-red-500"),title:Hh(e.id)?"Remove from favorites":"Add to favorites",children:(0,We.jsx)(O.A,{className:"h-5 w-5 ".concat(Hh(e.id)?"fill-current":"")})}),(0,We.jsx)(Tn,{minimal:!0,doc:e,canEdit:!0,documentSignaturesEnabled:es}),(0,We.jsx)(St.A,{type:"button",size:"md",leadingIcon:(0,We.jsx)(F.A,{className:"h-4 w-4"}),onClick:()=>nn(e),className:"inline-flex items-center px-4 py-2 border border-transparent text-sm rounded-md shadow-sm",children:"View Full Image"})]})]}),(0,We.jsxs)("div",{className:"bg-white p-4 rounded-lg border border-gray-200",children:[(0,We.jsx)("div",{className:"aspect-video w-full bg-gray-100 rounded-md flex items-center justify-center overflow-hidden",children:o?(0,We.jsx)("img",{src:o,alt:e.title||"Image",className:"max-w-full max-h-full object-contain",crossOrigin:"anonymous",onError:e=>{console.error("Error loading image:",e),e.target.style.display="none",e.target.parentNode.innerHTML='<div class="text-gray-500 text-sm text-center">Error loading image</div>'}}):(0,We.jsx)("div",{className:"text-sm text-gray-500",children:"No preview available"})}),((null===(n=e.info)||void 0===n?void 0:n.keyPoints)||[]).length>0&&(0,We.jsxs)("div",{className:"mt-4",children:[(0,We.jsx)("h3",{className:"font-medium text-gray-900 mb-2",children:"Key Points"}),(0,We.jsx)("ul",{className:"pl-5 list-disc text-sm text-gray-600 space-y-1",children:((null===(r=e.info)||void 0===r?void 0:r.keyPoints)||[]).map((e,t)=>(0,We.jsx)("li",{children:e},t))})]}),e.textContent&&"Image content - visual data only"!==e.textContent&&(0,We.jsxs)("div",{className:"mt-4",children:[(0,We.jsx)("h3",{className:"font-medium text-gray-900 mb-2",children:"Text Content"}),(0,We.jsx)("div",{className:"p-4 bg-gray-50 rounded-md text-sm text-gray-700 max-h-96 overflow-y-auto",children:(0,We.jsx)("pre",{className:"whitespace-pre-wrap font-sans leading-relaxed",children:e.textContent})})]})]})]})})(ar):"pdf"===ar.viewerMode?gf(ar):(ar.data_structure_and_organization&&((null===(V=ar.data_structure_and_organization.application_process)||void 0===V?void 0:V.steps)&&ar.data_structure_and_organization.application_process.steps.map((e,t)=>(0,We.jsx)("li",{className:"mb-1",children:e},t)),(null===(J=ar.data_structure_and_organization.payment_management)||void 0===J?void 0:J.details)&&ar.data_structure_and_organization.payment_management.details.map((e,t)=>(0,We.jsx)("li",{className:"mb-1",children:e},t)),ar.data_structure_and_organization.bonds&&ar.data_structure_and_organization.bonds.length>0&&ar.data_structure_and_organization.bonds.map((e,t)=>(0,We.jsxs)("tr",{className:t%2===0?"bg-white":"bg-blue-50",children:[(0,We.jsx)("td",{className:"px-4 py-2 text-sm text-gray-700",children:e.type}),(0,We.jsx)("td",{className:"px-4 py-2 text-sm text-gray-700",children:e.amount}),(0,We.jsx)("td",{className:"px-4 py-2 text-sm text-gray-700",children:e.expiration||e.renewal||"N/A"})]},t))),(0,We.jsx)("div",{className:"pb-5 border-gray-200 mb-6"}))};return(0,We.jsxs)("div",{className:"flex-1 h-screen overflow-hidden flex flex-col transition-all duration-200",children:[pu&&(0,We.jsx)("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-white/80 backdrop-blur-sm transition-opacity duration-200",children:(0,We.jsxs)("div",{className:"flex flex-col items-center gap-4 animate-fadeIn",children:[(0,We.jsx)("div",{className:"w-10 h-10 border-[3px] border-gray-200 border-t-blue-500 rounded-full animate-spin"}),(0,We.jsxs)("p",{className:"text-lg font-medium text-gray-700",children:["Switching to ",(0,We.jsx)("span",{className:"text-gray-900",children:pu})]})]})}),(0,We.jsx)(i.Suspense,{fallback:null,children:(0,We.jsx)(li,{suppress:Ui})}),wr&&An&&(0,We.jsxs)("div",{className:"fixed bottom-4 right-4 bg-black bg-opacity-80 text-white text-xs p-3 rounded-lg z-50 max-w-xs overflow-auto max-h-48",children:[(0,We.jsx)("div",{className:"font-bold mb-2",children:"\ud83d\udcf1 Mobile Debug"}),(0,We.jsxs)("div",{children:["currentPage: ",Ve||"null"]}),(0,We.jsxs)("div",{children:["currentDoc.id: ",(null===ar||void 0===ar?void 0:ar.id)||"null"]}),(0,We.jsxs)("div",{children:["hasEditorJson: ",null!==ar&&void 0!==ar&&ar.editorJson?"\u2705":"\u274c"]}),(0,We.jsxs)("div",{children:["documentLoading: ",ur?"\u23f3":"\u2705"]}),(0,We.jsxs)("div",{children:["idMatch: ",(null===ar||void 0===ar?void 0:ar.id)===Ve?"\u2705":"\u274c"]}),(0,We.jsxs)("div",{children:["isMobile: ",An?"\u2705":"\u274c"]}),(0,We.jsx)("button",{onClick:()=>{localStorage.removeItem("showMobileDebug"),kr(!1)},className:"mt-2 px-2 py-1 bg-red-600 rounded text-white",children:"Hide"})]}),(0,We.jsx)(To,{sidebarOpen:Ke,isMobile:An,currentPage:Ve,toggleSidebar:Yh,onAddKnowledge:dh,onCreateWithAI:mh,workspaceList:Or,setWorkspaceList:Fr,currentWorkspace:Lo,setCurrentWorkspaceObject:bd,setCurrentWorkspace:e=>{null!=e&&Ii(!0),_o(e)}
1,activeView:zo,setActiveView:Bo,fetchDocumentsForWorkspace:kg,firestore:G.db,currentWorkspaceObject:xd,currentUser:Z,setCurrentPage:Je,setCurrentDoc:ir,hasUnsavedChanges:fs,setShowUnsavedChangesModal:ws,setPendingNavigation:Ns,manualSaveTriggerRef:Cs,setActiveTab:Cr,knowledgeBase:Pn,deriveKeyFromCredential:Y.k5,decryptText:Y.PV,currentOrganizationId:ye,orgResolved:Ne,workspaceFetchCompleted:qo,onFetchWorkspacesComplete:Vo,formUnreadByWorkspace:th,selectedDocumentFolderId:El,onSelectDocumentFolder:(e,t)=>{null!=e&&Ii(!0);const n=t||null;n&&String(e)!==String(Lo)&&(hd.current=n),Il(n),"card"!==dn&&cn("card")},onCreateDocumentFolder:async(e,t)=>{await Zp(t,e)}}),(0,We.jsx)(la,{open:ym,onClose:fh,workspaceDocumentsForPicker:Wp,onCreateBlank:vh,onFormSubmit:Ah,onClarifySubmit:jh,onBackFromClarify:Nh,onIntegrationsContinue:wh,onEnableIntegration:kh,loading:Im,loadingMessage:Rm,integrationLookupLoading:np,phase:Nm,clarifyQuestions:_m,integrationSuggestedIds:Jm,integrationSnapshot:Km,integrationEnablingId:$m,showSignaturePadUnsureCheckbox:zp,initialPrompt:wm}),(0,We.jsx)(la,{flow:"update",getEditorForSuggestions:Ih,suggestUpdateWorkspaceId:"string"===typeof Lo&&"Default"!==Lo?Lo:(null===xd||void 0===xd?void 0:xd.id)||null,workspaceDocumentsForPicker:Wp,formSeedKey:Pp,formSeedDefaults:Op,initialUpdateUserPrompt:Up,open:up,onClose:Eh,onFormSubmit:Oh,onClarifySubmit:Fh,onBackFromClarify:Lh,onIntegrationsContinue:void 0,onEnableIntegration:void 0,loading:xp,loadingMessage:Ap,integrationLookupLoading:!1,phase:hp,clarifyQuestions:Sp,integrationSuggestedIds:[],integrationSnapshot:null,integrationEnablingId:null}),(0,We.jsxs)("div",{className:"flex-1 min-w-0 flex flex-col min-h-0 overflow-hidden transition-all duration-200 ".concat(Ke&&!An?"lg:ml-64":""," ").concat(Bd||qd||Qd?"mr-96":"mr-0"),children:[(0,We.jsxs)("div",{ref:Zc,className:"flex-1 min-h-0 flex flex-col overflow-y-auto",onScroll:Ve?e=>{nu(e.target.scrollTop>=120)}:void 0,children:[!(An&&Ve)&&(0,We.jsx)("div",{className:"border-b border-gray-200 bg-white shrink-0",children:(0,We.jsx)("div",{className:"px-4",children:(0,We.jsxs)("div",{className:"flex justify-between items-center h-[72px] gap-4",children:[Lo&&("card"===dn||"brainMap"===dn)&&(0,We.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[!An&&Ve&&(0,We.jsxs)("button",{type:"button",onClick:sh,className:"flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-100 transition-colors text-sm font-medium text-gray-700",title:"Back to all documents","aria-label":"Back to all documents",children:[(0,We.jsx)(U.A,{className:"h-4 w-4"}),(0,We.jsx)("span",{children:"Home"})]}),(e=>{if(An&&!Ve)return(0,We.jsxs)("button",{onClick:Yh,className:"flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-100 transition-colors text-sm font-medium text-gray-700","aria-label":Ke?"Close sidebar":"Open sidebar",children:[(0,We.jsx)(M.A,{className:"h-4 w-4"}),(0,We.jsx)("span",{className:"hidden sm:inline",children:"Workspaces"}),(0,We.jsx)("span",{className:"sm:hidden",children:"Workspaces"})]});let t=null;Lo&&("string"===typeof Lo?t=Lo:"object"===typeof Lo&&null!==Lo&&(t=Lo.id||Lo._id||Lo.workspaceId));const n=t&&"global"!==zo?((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).filter(e=>!!Array.isArray(e.workspaceIds)&&e.workspaceIds.some(e=>String(e)===String(t))):(null===Pn||void 0===Pn?void 0:Pn.documents)||[];if(0===n.length)return null;const r=(0,io.c3)(n,fl),o=(0,io.b4)(r);if(null===o||void 0===o||!o.categories||0===Object.keys(o.categories).length)return null;const a=null!==(e=null===Or||void 0===Or?void 0:Or.find(e=>String(e.id)===String(t)))&&void 0!==e?e:null,i="global"!==zo&&a&&["admin","editor"].includes(null===a||void 0===a?void 0:a.userRole);return(0,We.jsxs)("div",{className:"relative flex-shrink-0",ref:yu,children:[(0,We.jsxs)("button",{onClick:()=>Nc(!jc),className:"flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-100 transition-colors text-sm font-medium text-gray-700",children:[(0,We.jsx)(R.A,{className:"h-4 w-4"}),(0,We.jsx)("span",{className:"hidden sm:inline",children:"Table of Contents"}),(0,We.jsx)("span",{className:"sm:hidden",children:"TOC"}),(0,We.jsx)(y.A,{className:"h-4 w-4 transition-transform ".concat(jc?"rotate-180":"")})]}),jc&&(0,We.jsxs)("div",{className:"absolute left-0 top-full mt-2 w-80 max-h-[calc(100vh-8rem)] bg-white border border-gray-200 rounded-lg shadow-lg z-[9999] overflow-hidden flex flex-col",children:[(0,We.jsxs)("div",{className:"px-4 py-3 border-b border-gray-200 bg-gray-50 flex items-center justify-between",children:[(0,We.jsx)("h3",{className:"text-sm font-semibold text-gray-900",children:"Table of Contents"}),(0,We.jsx)("button",{onClick:()=>Nc(!1),className:"text-gray-400 hover:text-gray-600",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]}),(0,We.jsx)("div",{className:"overflow-y-auto px-3 py-3",style:{maxHeight:"calc(100vh - 12rem)"},children:tf("global"===zo?null:Lo,r,{onReorder:i?e=>{yl(e),"global"===zo&&null!==Z&&void 0!==Z&&Z.uid?(0,B.mZ)((0,B.doc)(G.db,"users",Z.uid),{globalGridDocumentOrder:e,updatedAt:(0,B.O5)()}).catch(e=>console.error("Failed to save global document order:",e)):t&&(0,B.mZ)((0,B.doc)(G.db,"workspaces",t),{gridD
1ocumentOrder:e,updatedAt:(0,B.O5)()}).catch(e=>console.error("Failed to save workspace document order:",e))}:void 0,categoryOrder:bl,onCategoryReorder:i?e=>{wl(e);const n={};r.forEach(e=>{var t;const r=(null===(t=e.info)||void 0===t?void 0:t.category)||e.category||"Uncategorized";(n[r]||(n[r]=[])).push(e.id)});const o=[];e.forEach(e=>{n[e]&&o.push(...n[e])}),Object.keys(n).forEach(t=>{e.includes(t)||o.push(...n[t])}),yl(o),"global"===zo&&null!==Z&&void 0!==Z&&Z.uid?(0,B.mZ)((0,B.doc)(G.db,"users",Z.uid),{globalCategoryOrder:e,globalGridDocumentOrder:o,updatedAt:(0,B.O5)()}).catch(e=>console.error("Failed to save global category order:",e)):t&&(0,B.mZ)((0,B.doc)(G.db,"workspaces",t),{categoryOrder:e,gridDocumentOrder:o,updatedAt:(0,B.O5)()}).catch(e=>console.error("Failed to save workspace category order:",e))}:void 0})})]})]})})()]}),"continuous"===dn&&(0,We.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[!An&&Ve&&(0,We.jsxs)("button",{type:"button",onClick:sh,className:"flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-100 transition-colors text-sm font-medium text-gray-700",title:"Back to all documents","aria-label":"Back to all documents",children:[(0,We.jsx)(U.A,{className:"h-4 w-4"}),(0,We.jsx)("span",{children:"Home"})]}),An&&!Ve?(0,We.jsxs)("button",{onClick:Yh,className:"flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-100 transition-colors text-sm font-medium text-gray-700","aria-label":Ke?"Close sidebar":"Open sidebar",children:[(0,We.jsx)(M.A,{className:"h-4 w-4"}),(0,We.jsx)("span",{className:"hidden sm:inline",children:"Workspaces"}),(0,We.jsx)("span",{className:"sm:hidden",children:"Workspaces"})]}):(0,We.jsxs)("div",{className:"relative flex-shrink-0",ref:yu,children:[(0,We.jsxs)("button",{ref:Ic,onClick:()=>Nc(!jc),className:"flex items-center gap-2 px-3 py-2 rounded-md hover:bg-gray-100 transition-colors text-sm font-medium text-gray-700",children:[(0,We.jsx)(R.A,{className:"h-4 w-4"}),(0,We.jsx)("span",{className:"hidden sm:inline",children:"Table of Contents"}),(0,We.jsx)("span",{className:"sm:hidden",children:"TOC"}),(0,We.jsx)(y.A,{className:"h-4 w-4 transition-transform ".concat(jc?"rotate-180":"")})]}),jc&&"undefined"!==typeof document&&(0,s.createPortal)((0,We.jsxs)("div",{className:"toc-dropdown-portal fixed w-80 bg-white border border-gray-200 rounded-lg shadow-lg overflow-hidden flex flex-col",style:{left:"".concat(Tc.left,"px"),top:"".concat(Tc.top,"px"),maxHeight:"calc(100vh - ".concat(Tc.top+16,"px)"),height:"auto",zIndex:999999,position:"fixed",isolation:"isolate"},"data-toc-dropdown":"true",children:[(0,We.jsxs)("div",{className:"px-4 py-3 border-b border-gray-200 bg-gray-50 flex items-center justify-between flex-shrink-0",children:[(0,We.jsx)("h3",{className:"text-sm font-semibold text-gray-900",children:"Table of Contents"}),(0,We.jsx)("button",{onClick:()=>Nc(!1),className:"text-gray-400 hover:text-gray-600",children:(0,We.jsx)(c.A,{className:"h-4 w-4"})})]}),(0,We.jsx)("div",{ref:Ec,className:"overflow-y-auto px-3 py-3 flex-1",style:{minHeight:"200px"},children:Ec.current&&!Ec.current.hasChildNodes()&&(0,We.jsx)("div",{className:"text-sm text-gray-500 py-4",children:"Loading table of contents..."})})]}),document.body)]})]}),!(An&&!Ve)&&(0,We.jsx)("div",{className:"flex-1 max-w-2xl mx-4",children:(0,We.jsx)(Po,{value:dt,onQueryChange:ct,isSearching:yt,placeholder:"Search all documents...",onSubmit:Zh})}),(0,We.jsx)("div",{className:"flex items-center flex-shrink-0 space-x-3",children:(0,We.jsx)(Va,{userProfile:le,profileMenuOpen:et,setProfileMenuOpen:tt,currentOrganizationId:ye,organizationId:ue,setCurrentOrganizationId:ve,setOrganizationId:fe,currentUserRole:xe,hasUnseenUpdates:we,appUpdatesVersion:Ae,appUpdatesIsBeta:je,onShowWhatsNew:()=>at(!0),onLogout:Bh,profileMenuRef:Kh,showExportData:Co,onExportData:()=>Ai(!0),resetViewOnOrgSwitch:e=>{(0,W.gg)('[OrgSwitch] resetViewOnOrgSwitch: clearing state, showing overlay for "'.concat(e,'"')),du.current=!0,cu.current=Or,gu(e||"organization"),hu.current=e||"organization",fu.current&&clearTimeout(fu.current),fu.current=setTimeout(()=>{(0,W.gg)("[OrgSwitch] Overlay safety timeout reached, dismissing"),gu(null),hu.current=null,du.current=!1},8e3),qt(),Je(null),ir(null),_o(null),Ii(!1),null!==X&&void 0!==X&&X.uid&&(0,en.NH)(X.uid)}})})]})})}),(0,We.jsx)("main",{className:"flex flex-col ".concat("brainMap"===dn||"continuous"===dn?"px-4 sm:px-6 lg:px-8 pt-6 pb-16":!Ve||dt.trim()&&(yt||wt)?"px-4 sm:px-6 lg:px-8 flex-1 min-h-0 pt-6 pb-16":"px-0 flex-1 min-h-0 pt-0 pb-6 shrink-0"),children:"brainMap"===dn||"continuous"===dn?(0,We.jsx)("div",{className:"max-w-3xl lg:max-w-5xl w-full pb-8",children:mf()}):"card"===dn?!Ve||dt.trim()&&(yt||wt)?(0,We.jsx)("div",{className:"max-w-3xl lg:max-w-5xl pb-12",children:t()}):ar&&("pdf"===ar.viewerMode&&ar.id||(An?ar.editorJson&&ar.id:ar.id===Ve||ar.editorJson&&ar.id))?Bc?"pdf"===ar.viewerMode?(0,We.jsx)("div",{className:"flex flex-col flex-1 min-h-0 w-full",children:gf(ar)}):(0,We.jsxs)(We.Fragment,{children:[Im&&!ym&&Ve&&(0,We.jsxs)("div",{role:"status","aria-live":"polite",className:"flex items-center gap-2.5 border-b border-blue-100 bg-blue-50/95 px-4 sm:px-6 py-2.5 text-sm text-blue-900 shrink-0",children:[(0,We.jsx)(Se.y$,{size:"sm",className:"text-blue-600 shrink-0","aria-hidden":!0}),(0,We.jsx)("span",{children:ip?"Writing your document\u2026":"Connecting\u2026"})]}),(0,W.gg)("\ud83d\udd0d DOCUMENT STATE COMPARISON:",{currentPage:Ve,currentPageCategeory:null===ar||void 0===ar?void 0:ar.category,currentDocId:null===ar||void 0===ar?void 0:ar.id,mismatch:Ve!==(null===ar||void 0===ar?void 0:ar.id),currentDocTitle:null===ar||void 0===ar?void 0:ar.title,currentDocIsNew:null===ar||void 0===ar?void 0:ar.isNew,timestamp:Date.now()}),(0,W.gg)("\ud83d\udd0d CURRENT DOC BEFORE EDITOR:",{id:null===ar||void 0===ar?void 0:ar.id,title:null===ar||void 0===ar?void 0:ar.title,hasEditorJson:!(null===ar||void 0===ar||!ar.editorJson),hasUserEncrypted:!(null===ar||void 0===ar||!ar.userEncryptedResult),hasEncrypted:!(null===ar||void 0===ar||!ar.encryptedResult),isDecrypted:null===ar||void 0===ar?void 0:ar.isDecrypted,allFields:Object.keys(ar||{})}),(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,oe.z7)(ar)?(0,We.jsx)(si,{currentDoc:ar,currentUser:Z,organizationId:ue||ye,versionControlEnabled:Yi&&!Ag,versionControlReady:Zi,workspaceName:(Array.isArray(null===ar||void 0===ar?void 0:ar.workspaceIds)?ar.workspaceIds.map(e=>{var t;return null===Or||void 0===Or||null===(t=Or.find(t=>
1t.id===e))||void 0===t?void 0:t.name}).filter(Boolean).join(", "):"")||(null===ar||void 0===ar?void 0:ar.workspace)||(null===Or||void 0===Or||null===(ff=Or.find(e=>e.id===Lo))||void 0===ff?void 0:ff.name)||"",onSaved:e=>{ir(e),ys(!1)},onTitleChange:e=>{ir(t=>t?(0,o.A)((0,o.A)({},t),{},{title:e}):t)},onCategoryChange:oh,categoryPresets:ps,onWorkspaceChange:jg,availableWorkspaces:(null===Or||void 0===Or?void 0:Or.map(e=>e.name))||[],workspaceList:Or,onCreateWorkspace:Zg,onNavigateBack:sh}):(0,We.jsx)(ii,{categoryStagingRef:lr,scrollContainerInParent:!0,stickyTopOffset:"0",toolbarSticky:eu,onScrollReport:e=>nu(e>=120),editorAreaLeftOffset:Ke&&!An?256:0,docActionsContainerRef:Hc,docActionsContainerReady:Qc,setDocActionsContainerReady:Yc,pdfExportEnabled:Xi,onExportPdf:Vp,isGeneratingPdf:Jc,paymentConfigOpen:$u,setPaymentConfigOpen:Xu,paymentConfigUpdating:em,updateDocumentPaymentConfig:um,paymentFixedAmountEditing:tm,setPaymentFixedAmountEditing:nm,paymentSubscriptionAmountEditing:rm,setPaymentSubscriptionAmountEditing:om,paymentSubscriptionEnabledEffective:dm,onPlacePaymentButton:()=>{var e,t;null===(e=mm.current)||void 0===e||null===(t=e.insertPaymentButton)||void 0===t||t.call(e),Xu(!1)},paymentButtonRef:cm,onAISidebarOpenChange:Hd,minimalUI:An,currentDoc:ru,currentUser:Z,onTitleUpdate:(e,t)=>{const n=t||Ve;n&&e&&Ng(e,n)},onTitleAnimationUpdate:Yg,onCategoryUpdate:(e,t)=>Cg(Ve,e,t),onSave:async function(e,t,n,r){let a=arguments.length>4&&void 0!==arguments[4]&&arguments[4];const i=(0,o.A)((0,o.A)({},e),{},{id:Ve}),s=await ah(i,t,n,r,a);return null!==s&&void 0!==s&&s.skipped?s:(null!==s&&void 0!==s&&s.id&&s.id!==Ve&&Je(s.id),null!==s&&void 0!==s&&s.isEncrypted||ir(e=>{const t=null!==e&&void 0!==e?e:{},n=t.isDecrypted?{editorJson:t.editorJson,editorHtml:t.editorHtml,isDecrypted:t.isDecrypted}:{};(0,W.gg)("\ud83d\udd0d SETCURRENTDOC DEBUG:",{baseIsDecrypted:t.isDecrypted,preserveDecryptedFields:Object.keys(n),savedFields:Object.keys(s||{}),baseHasEditorJson:!!t.editorJson,savedHasEditorJson:!(null===s||void 0===s||!s.editorJson)});const r=null!==s&&void 0!==s&&s.isEncrypted&&null!==s&&void 0!==s&&s.encryptedResult?{encryptedResult:s.encryptedResult}:{};return(0,o.A)((0,o.A)((0,o.A)((0,o.A)((0,o.A)({},t),s),n),r),{},{id:(null===s||void 0===s?void 0:s.id)||Ve},null!==e&&void 0!==e&&e.category&&(null===s||void 0===s?void 0:s.updatedAt)<=(null===e||void 0===e?void 0:e.updatedAt)?{category:e.category}:{})}),localStorage.removeItem("knowledgeBase"),iu(!0),(0,o.A)((0,o.A)({},i),s))},onContentUpdate:e=>{ir(t=>(0,o.A)((0,o.A)({},t),{},{editorJson:e}))},onCategoryChange:oh,categoryPresets:ps,onWorkspaceChange:jg,availableWorkspaces:(null===Or||void 0===Or?void 0:Or.map(e=>e.name))||[],workspaceList:Or,isSaving:"Saving..."===_n,onCreateWorkspace:Zg,onNavigateBack:sh,hasUnsavedChanges:fs,setHasUnsavedChanges:ys,onManualSaveReady:e=>{Cs.current=e},onEditorActionsReady:e=>{mm.current=e},bridgeEditorRef:pm,onAIGeneratedToolbarDismiss:Th,onAIStartFromScratch:Ch,onOpenUpdateWithAI:rs?Dh:void 0,onOpenAIRevisionPromptBar:Sh,onCloseAIRevisionBar:Ph,onAIRevisionSubmit:_h,onShare:Ag?void 0:Bu,versionControlEnabled:Yi&&!Ag,versionControlReady:Zi,timerEnabled:$i,mascotEnabled:us,agentAutoStartTimerTaskName:Pt,onAgentAutoStartTimerConsumed:ms,documentSignaturesEnabled:es,autoTitleEnabled:ns,autoCategoryEnabled:null!==(yf=null===Qi||void 0===Qi?void 0:Qi.autoCategoryEnabled)&&void 0!==yf&&yf,sopEnhancementEnabled:rs,voiceEnabled:os,pexelsEnabled:as,formsEnabled:is,templateFillEnabled:ss,envVaultEnabled:ls,onEnvVaultClick:ch,accessibleWorkspaceIds:(null===Or||void 0===Or?void 0:Or.map(e=>e.id))||[],onOpenFilledDocument:e=>{if(null===e||void 0===e||!e.id)return;ys(!1),ir(e),Je(e.id);const t=e._sourceTemplateId;Rn(n=>{if(null===n||void 0===n||!n.documents)return{documents:[e],structure:{},processed:!0};let r=n.documents.slice();const a=r.findIndex(t=>t.id===e.id);return a>=0?r[a]=(0,o.A)((0,o.A)({},r[a]),e):r=[e,...r],t&&(r=r.map(e=>e.id===t?(0,o.A)((0,o.A)({},e),{},{isTemplate:!0}):e)),(0,o.A)((0,o.A)({},n),{},{documents:r})}),(0,H.gc)(Fe,Or).then(e=>{null!==e&&void 0!==e&&e.documents&&Rn(e)}).catch(()=>{})},stripeIntegrationConnected:ds,stripeHourlyRate:cs,documentLockEnabled:ts,onLockDocument:ts&&ue?async e=>{const t=await Promise.resolve().then(n.bind(n,52395)),r=t.getFunctions,a=(0,t.httpsCallable)(r(),"lockDocument");await a({documentId:e,organizationId:ue}),ir(e=>e?(0,o.A)((0,o.A)({},e),{},{locked:!0}):e),Rn(t=>null!==t&&void 0!==t&&t.documents?(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>
1t.id===e?(0,o.A)((0,o.A)({},t),{},{locked:!0}):t)}):t)}:void 0,onUnlockDocument:ts&&ue?async(e,t)=>{await(0,H.w5)(e,ue,t),ir(e=>e?(0,o.A)((0,o.A)({},e),{},{locked:!1}):e),Rn(t=>null!==t&&void 0!==t&&t.documents?(0,o.A)((0,o.A)({},t),{},{documents:t.documents.map(t=>t.id===e?(0,o.A)((0,o.A)({},t),{},{locked:!1}):t)}):t)}:void 0,onDelete:async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{(0,W.gg)("\ud83d\uddd1\ufe0f Deleting document from editor:",e),await(0,H.Nn)(e,t);const r=await(0,H.gc)(Fe,Or);if(Rn(r),dt.trim())try{const e=await(0,H.mR)(dt,Or);gt(e)}catch(n){console.error("Search refresh after delete:",n),gt([])}Je(null),ir(null),Ie.Ay.success("Document deleted successfully"),(0,W.gg)("\u2705 Document deleted and navigated back to knowledge base")}catch(r){throw console.error("\u274c Error deleting document:",r),r}}},(()=>{if(null!==Ve&&void 0!==Ve&&Ve.startsWith("new_"))return Qs.current=Ve,Ve;const e=Ks.current.get(Ve);return e||(Qs.current!==Ve&&Qs.current?Qs.current=Ve:Qs.current||(Qs.current=Ve),Qs.current||Ve)})())})]}):(0,We.jsx)("div",{className:"prose",children:t()}):t():null})]}),(0,We.jsx)(Ye,{knowledgeBase:(null===Pn||void 0===Pn?void 0:Pn.id)===Lo?Pn:(0,o.A)((0,o.A)({},Pn),{},{id:Lo}),isOpen:Fu,onClose:Yu,onSave:Vu,onDelete:Eu?()=>Gu(Eu):void 0,currentLink:Ju,workspaceId:Lo,workspaceName:null!==(vf=null===xd||void 0===xd?void 0:xd.name)&&void 0!==vf?vf:"",documentId:_u,documentOnlyShare:!!_u,organizationId:(null===xd||void 0===xd?void 0:xd.organizationId)||ue,preferredExternalAgentId:dc,mascotEnabled:us}),(0,We.jsx)(Na,{isOpen:qa&&!!Lo&&!!xd,workspaceId:Lo,workspaceName:null===xd||void 0===xd?void 0:xd.name,organizationId:(null===xd||void 0===xd?void 0:xd.organizationId)||ue,currentUserRole:(null===xd||void 0===xd?void 0:xd.userRole)||"viewer",onClose:()=>Ha(!1)}),(0,We.jsx)(Qa,{isOpen:fi,onClose:()=>Ai(!1),organizationId:ye||ue,organizationName:Wi||"",isOrgAdmin:"admin"===xe,exportableWorkspaces:No}),(0,We.jsx)(Yt,{isOpen:pg,onClose:()=>gg(!1),onSelect:hg,currentEmoji:(null===xd||void 0===xd?void 0:xd.emoji)||null}),(0,We.jsx)(Ct,{isOpen:bu,onClose:()=>wu(!1),workspaceId:Lo,linkId:(null===(xf=ju[0])||void 0===xf?void 0:xf.linkId)||null,knowledgeBaseTitle:(null===xd||void 0===xd?void 0:xd.name)||"Knowledge Base",initialShareBranding:null!==(bf=null===(wf=ju[0])||void 0===wf?void 0:wf.shareBranding)&&void 0!==bf?bf:null}),(0,We.jsx)(It,{isOpen:ot,onClose:()=>at(!1),onMarkAsSeen:it}),(0,We.jsx)(i.Suspense,{fallback:null,children:(0,We.jsx)(di,{isOpen:Ui,onComplete:Ue,onSkip:Me,organizationId:ue||(0,Pe.getSelectedOrganizationId)(),initialOrgName:Wi,initialOrgLogoUrl:Hi})}),(0,We.jsx)(So,{isOpen:!!zg,onClose:()=>Bg(null),docId:null===zg||void 0===zg?void 0:zg.id,title:null===zg||void 0===zg?void 0:zg.title,fileName:null===zg||void 0===zg?void 0:zg.fileName,setCoverImageUrl:Dg,setCoverImagePosition:Pg,clearCoverImage:Tg,searchPexelsForCover:Rg,randomPexelsCoverImage:Og,cycleDocumentCoverImage:Fg,fetchCoverImage:Eg}),(0,We.jsx)(Dn.R,{isOpen:$o,title:null===na||void 0===na||null===(kf=na.doc)||void 0===kf||!kf.locked||null!==na&&void 0!==na&&na.isGlobalView?null!==na&&void 0!==na&&na.isGlobalView?"Delete Document":"Remove Document":"Unlock document",message:null===na||void 0===na||null===(Af=na.doc)||void 0===Af||!Af.locked||null!==na&&void 0!==na&&na.isGlobalView?null!==na&&void 0!==na&&na.isGlobalView?null!==na&&void 0!==na&&null!==(Nf=na.doc)&&void 0!==Nf&&Nf.locked?'This document is locked. Type "unlock document" below, then click "Unlock and delete" to permanently delete "'.concat(null===na||void 0===na?void 0:na.docTitle,'".'):(0,oe.z7)(null===na||void 0===na?void 0:na.doc)?'This secrets document cannot be deleted accidentally. Type "'.concat(ae.ZE,'" below, then click Delete to permanently delete "').concat(null===na||void 0===na?void 0:na.docTitle,'".'):'Are you sure you want to permanently delete "'.concat(null===na||void 0===na?void 0:na.docTitle,'"?'):'Remove "'.concat(null===na||void 0===na?void 0:na.docTitle,'" from the "').concat(null===na||void 0===na||null===(Cf=na.workspaceData)||void 0===Cf?void 0:Cf.name,'" workspace?'):'Type "unlock document" below to unlock this document. Then you can remove it from the "'.concat(null===na||void 0===na||null===(jf=na.workspaceData)||void 0===jf?void 0:jf.name,'" workspace.'),onConfirm:null===na||void 0===na||null===(Sf=na.doc)||void 0===Sf||!Sf.locked||null!==na&&void 0!==na&&na.isGlobalView?Jp:tg,onCancel:()=>{Xo(!1),ra(null),sa(""),ba(null)},confirmText:null===na||void 0===na||null===(Ef=na.doc)||void 0===Ef||!Ef.locked||null!==na&&void 0!==na&&na.isGlobalView?null!==na&&void 0!==na&&na.isGlobalView?null!==na&&void 0!==na&&null!==(If=na.doc)&&void 0!==If&&If.locked?"Unlock and delete":"Delete":"Remove":"Unlock",showUnlockPhraseInput:Ca.showInput,unlockPhrase:ia,onUnlockPhraseChange:sa,unlockPhraseError:fa,unlockPhraseLabel:Ca.label,unlockPhrasePlaceholder:Ca.placeholder,requiredPhrase:Ca.requiredPhrase,isConfirming:Aa}),(0,We.jsx)(Oo,{isOpen:!!Tl,folder:Tl,documentCount:Tl?((null===Pn||void 0===Pn?void 0:Pn.documents)||[]).filter(e=>Ft(e)===Tl.id).length:0,onConfirm:eg,onCancel:()=>{Ll||Rl(null)},isConfirming:Ll}),(0,We.jsx)(Dn.R,{isOpen:Ta,title:"Delete documents",message:"Are you sure you want to permanently delete ".concat(jl.size," document").concat(1===jl.size?"":"s","? This cannot be undone."),onConfirm:qp,onCancel:()=>Ra(!1),confirmText:"Delete",confirmVariant:"danger",isConfirming:za}),(0,We.jsx)(Dn.R,{isOpen:La,title:"Remove from workspace",message:"Remove ".concat(jl.size," document").concat(1===jl.size?"":"s"," from this workspace?"),onConfirm:Hp,onCancel:()=>_a(!1),confirmText:"Remove",confirmVariant:"danger",isConfirming:za})]}),(0,We.jsx)(Ia,{isOpen:Bd,currentWorkspaceObject:xd,currentWorkspace:Lo,sidebarFilteredDocs:Bp,onClose:Mc,userProfile:le,activeDocumentId:yr}),fc&&(0,We.jsx)("div",{className:"fixed inset-0 bg-black bg-opacity-50 z-[80] flex items-center justify-center p-4",onClick:()=>{yc(!1),pc(null)},children:(0,We.jsxs)("div",{className:"bg-white rounded-lg max-w-6xl w-full max-h-[90vh] overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,We.jsxs)("div",{className:"flex justify-between items-center p-4 border-b border-gray-200",children:[(0,We.jsx)("h2",{className:"text-xl font-semibold",children:mc?"Edit Agent":"Create New Agent"}),(0,We.jsx)("button",{onClick:()=>{yc(!1),pc(null)},className:"text-gray-500 hover:text-gray-700 p-1",children:(0,We.jsx)(c.A,{className:"w-6 h-6"})})]}),(0,We.jsx)("div",{className:"overflow-auto max-h-[calc(90vh-80px)]",children:(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,We.jsx)(ai,{workspace:Lo,existingAgent:mc,onSave:()=>{yc(!1),pc(null),wc(e=>e+1)},onDelete:()=>{yc(!1),pc(null),wc(e=>e+1)}})})})]})}),Xt&&(0,We.jsx)(Eo,{className:"fixed inset-0 z-70 flex items-center justify-center bg-black bg-opacity-75",image:Xt,onClose:()=>nn(null)}),(0,We.jsx)(va,{isOpen:bs,onClose:()=>{ws(!1),Ns(null)},onLeave:()=>{ws(!1),ys(!1),js&&(js(),Ns(null))},onSave:async()=>
1{if(Cs.current&&!Ps){Ts(!0);try{await Cs.current();let e=0;const t=50;for(;Rs.current&&e<t;)await new Promise(e=>setTimeout(e,100)),e++;if(!Rs.current||e>=t){if(ws(!1),js&&(js(),Ns(null)),e>=t&&Rs.current)return Ie.Ay.error("Save may not have completed. Please check and try again."),void Ts(!1);Ie.Ay.success("Document saved successfully")}}catch(e){console.error("Save failed:",e),Ie.Ay.error("Failed to save. Please try again.")}finally{Ts(!1)}}},isSaving:Ps}),(0,We.jsx)(xa,{isOpen:Ls,validationWarning:Js,onCancel:()=>{_s(!1),Bs(null),qs(null),Un(null)},onSaveAnyway:async()=>{zs&&(_s(!1),await ah(zs.dataToSave,zs.html,zs.title,zs.isUpdate,zs.isManualSave,!0),Bs(null),qs(null))}})]})}if(!Z&&!X)return de?(0,We.jsx)("div",{className:"flex items-center justify-center min-h-screen",children:(0,We.jsxs)("div",{className:"flex flex-col items-center gap-4",children:[(0,We.jsx)(Se.y$,{size:"lg",className:"text-blue-600"}),(0,We.jsx)("p",{className:"text-gray-500 text-sm",children:"Loading..."})]})}):(0,We.jsx)(i.Suspense,{fallback:mi,children:(0,We.jsx)(ni,{})})}},23524(e,t,n){n.d(t,{Q:()=>i,R:()=>s});n(65043);var r=n(97950),o=n(66630),a=n(70579);const i=e=>{let t=e.children;if("undefined"===typeof document)return null;let n=document.getElementById("modal-root");return n||(n=document.createElement("div"),n.id="modal-root",document.body.appendChild(n)),(0,r.createPortal)(t,n)};function s(e){let t=e.isOpen,n=e.title,r=e.message,s=e.onConfirm,l=e.onCancel,d=e.confirmText,c=void 0===d?"Delete":d,u=e.confirmVariant,m=void 0===u?"danger":u,p=e.showUnlockPhraseInput,g=void 0!==p&&p,h=e.unlockPhrase,f=void 0===h?"":h,y=e.onUnlockPhraseChange,v=e.unlockPhraseError,x=void 0===v?null:v,b=e.unlockPhraseLabel,w=void 0===b?"Unlock phrase":b,k=e.unlockPhrasePlaceholder,A=void 0===k?"Enter the document unlock phrase":k,j=e.requiredPhrase,N=void 0===j?null:j,C=e.isConfirming,S=void 0!==C&&C;if(!t)return null;const E="danger"===m?"text-white bg-red-500 hover:bg-red-600":"text-white bg-indigo-600 hover:bg-indigo-700",I=null!=f?String(f):"",D=!(!g||(N?I===N:""!==I.trim()))||S;return(0,a.jsx)(i,{children:(0,a.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50",children:(0,a.jsxs)("div",{className:"bg-white rounded-lg shadow-lg p-6 w-full max-w-md",children:[(0,a.jsx)("h3",{className:"text-lg font-medium mb-2",children:n}),(0,a.jsx)("p",{className:"text-gray-600 mb-4",children:r}),S&&(0,a.jsx)("p",{className:"text-sm text-gray-500 mb-4","aria-live":"polite",children:"Working\u2026"}),g&&(0,a.jsxs)("div",{className:"mb-4",children:[(0,a.jsx)("label",{htmlFor:"unlock-phrase",className:"block text-sm font-medium text-gray-700 mb-1",children:w}),(0,a.jsx)("input",{id:"unlock-phrase",type:"text",value:f,onChange:e=>null===y||void 0===y?void 0:y(e.target.value),placeholder:A,disabled:S,className:"block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-red-500 focus:border-red-500 sm:text-sm disabled:bg-gray-100 disabled:cursor-not-allowed",autoComplete:"off"}),x&&(0,a.jsx)("p",{className:"mt-1 text-sm text-red-600",children:x})]}),(0,a.jsxs)("div",{className:"flex justify-end space-x-2",children:[(0,a.jsx)("button",{onClick:l,disabled:S,className:"px-4 py-2 text-sm text-gray-700 bg-gray-100 hover:bg-gray-200 rounded disabled:opacity-50 disabled:cursor-not-allowed",children:"Cancel"}),(0,a.jsxs)("button",{onClick:s,disabled:D,className:"inline-flex items-center justify-center gap-2 px-4 py-2 text-sm rounded disabled:opacity-50 disabled:cursor-not-allowed ".concat(E),children:[S&&(0,a.jsx)(o.y$,{size:"sm",className:"flex-shrink-0"}),c]})]})]})})})}},84980(e,t,n){n.d(t,{Hx:()=>l,L$:()=>a,b4:()=>i,c3:()=>d});var r=n(89379),o=n(60678);function a(e,t){const n="string"===typeof t.category&&t.category.trim().length>0;if(!e)return n?t:(0,r.A)((0,r.A)({},t),{},{category:""});return"string"===typeof e.category&&e.category.trim().length>0&&!n?(console.trace("\ud83d\udee1\ufe0f Blocked category overwrite",{id:e.id,prev:e.category,incoming:t.category}),(0,r.A)((0,r.A)({},t),{},{category:e.category})):t}function i(){const e={categories:{}};return(arguments.length>
10&&void 0!==arguments[0]?arguments[0]:[]).forEach(t=>{const n=t.category||"Uncategorized",r=t.subcategory||"General";e.categories[n]||(e.categories[n]={subcategories:{}}),e.categories[n].subcategories[r]||(e.categories[n].subcategories[r]=[]),e.categories[n].subcategories[r].push(t)}),e}function s(e){const t=(0,o.B0)(e);if(t)return t;const n=(0,o.W0)(e.addedAt)||(0,o.W0)(e.timestamp);return n||new Date}function l(e){const t=e.fileType||"",n=e.source||e.captureSource||"",r=e.category||"";if(!t&&!n.includes("chrome")&&!n.includes("extension"))return"Document";if(n.includes("chrome")||n.includes("extension")||"voice"===r)return"Voice";switch(t){case"text/plain":return"Text";case"application/pdf":return"PDF";case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":case"application/msword":return"Word";case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":case"application/vnd.ms-excel":case"text/csv":return"Excel";case"application/vnd.openxmlformats-officedocument.presentationml.presentation":case"application/vnd.ms-powerpoint":return"PPT";case"application/json":return"JSON";default:return t.startsWith("audio/")?"Audio":t.startsWith("video/")?"Video":t.startsWith("image/")?"Image":t.startsWith("text/")?"Text":"File"}}function d(e,t){if(t&&t.length>0){const n=new Map;t.forEach((e,t)=>{n.set(e,t)});const r=[...e].sort((e,t)=>{const n=s(e);return s(t)-n}),o=new Map;r.forEach(e=>{o.set(e.id,e)});const a=[],i=[];r.forEach(e=>{n.has(e.id)?a.push(e):i.push(e)});const l=[],d=new Set,c=Math.max(...t.map((e,t)=>t),e.length-1);let u=0;for(let e=0;e<=c;e++){const n=t[e];n&&o.has(n)&&!d.has(n)?(l.push(o.get(n)),d.add(n)):u<i.length&&(l.push(i[u]),u++)}for(;u<i.length;)l.push(i[u]),u++;return l}return[...e].sort((e,t)=>{const n=s(e);return s(t)-n})}},98315(e,t,n){n.d(t,{K:()=>v});var r=n(89379),o=n(5544),a=n(65043),i=n(47874),s=n(55472),l=n(67898),d=n(92339),c=n(13471),u=n(96822),m=n(47081),p=n(1862),g=n(70579);const h=[{id:"mon",label:"Mon"},{id:"tue",label:"Tue"},{id:"wed",label:"Wed"},{id:"thu",label:"Thu"},{id:"fri",label:"Fri"},{id:"sat",label:"Sat"},{id:"sun",label:"Sun"}];function f(e,t){return!!(t&&e&&Array.isArray(e.workspaces))&&e.workspaces.some(e=>e&&String(e.id)===String(t))}async function y(e){if(!e)return"";try{const t=await(0,s.getDoc)((0,s.doc)(u.db,"users",e));if(!t.exists())return"";const n=t.data();if(n&&"string"===typeof n.profileImageUrl&&n.profileImageUrl.trim())return n.profileImageUrl.trim()}catch(t){(0,p.gg)("fetchUserProfileImageUrl:",t)}return""}function v(e){let t=e.value,n=void 0===t?{}:t,p=e.onChange,v=e.disabled,x=void 0!==v&&v,b=e.onUploadTeamMemberPhoto,w=e.showTitle,k=void 0===w||w,A=e.introText,j=void 0===A?"Defaults (team, notifications, messages) apply everywhere. Turn on each surface independently: embed vs shared workspace links.":A,N=e.surfaceScope,C=void 0===N?"both":N,S=e.hideShareSurfaceToggle,E=void 0!==S&&S,I=e.hideSurfaceToggles,D=void 0!==I&&I,P=e.workspaceId,T=void 0===P?null:P;const R=n,O="shareOnly"===C,F=(0,i.Zp)(),L=(0,a.useState)([]),_=(0,o.A)(L,2),U=_[0],M=_[1],z=(0,a.useState)(!1),B=(0,o.A)(z,2),W=B[0],V=B[1],J=(0,a.useState)(0),q=(0,o.A)(J,2),H=q[0],G=q[1],K=(0,a.useState)(null),Q=(0,o.A)(K,2),Y=Q[0],Z=Q[1],$=(0,a.useState)(!1),X=(0,o.A)($,2),ee=X[0],te=X[1],ne=(0,a.useCallback)(e=>{null===p||void 0===p||p(e)},[p]),re=D?!!R.liveRequestsEmbedEnabled:O?!!R.liveRequestsShareLinkEnabled:!(!R.liveRequestsEmbedEnabled&&!R.liveRequestsShareLinkEnabled);(0,a.useEffect)(()=>{let e=!1;return async function(){if(T&&re){V(!0);try{var t;const n=await(0,s.getDoc)((0,s.doc)(u.db,"workspaces",T));if(!n.exists())return void(e||M([]));const r=null===(t=n.data())||void 0===t?void 0:t.organizationId;if(!r)return void(e||M([]));const o=await(0,m.fP)(r);e||M(Array.isArray(o)?o:[])}catch(n){console.error("LiveChatHandoffWorkspaceForm: loadOrgMembers",n),e||(M([]),d.Ay.error("Could not load organization members"))}finally{e||V(!1)}}else M([])}(),()=>{e=!0}},[T,re]),(0,a.useEffect)(()=>{let e=!1;return async function(){var t;if(!re||x||W)return;const n=null===(t=(0,l.xI)().currentUser)||void 0===t?void 0:t.uid;if(!n)return;if(1!==U.length)return;if(String(U[0].id)!==String(n))return;const o=R.liveRequestTeamMembers||[],a=o.filter(e=>!e.userId);if(1!==a.length)return;const i=a[0],s=U[0];let d=(i.avatarUrl||"").trim();if(d||(d=await y(n)||""),e)return;const c=(i.linkedEmail||s.email||"").trim();ne({liveRequestTeamMembers:o.map(e=>e.id===i.id?(0,r.A)((0,r.A)((0,r.A)({},e),{},{userId:n},c?{linkedEmail:c}:{}),d?{avatarUrl:d}:{}):e)})}(),()=>{e=!0}},[U,W,R.liveRequestTeamMembers,re,x,ne]);const oe=(0,a.useCallback)(async e=>{const t=e.id,n=await y(t);ne({liveRequestTeamMembers:[...R.liveRequestTeamMembers||[],{id:"undefined"!==typeof crypto&&crypto.randomUUID?crypto.randomUUID():"tm_".concat(Date.now(),"_").concat(Math.random().toString(36).slice(2,9)),name:e.name&&String(e.name).trim()?String(e.name).trim():"",role:"",avatarUrl:n||"",userId:t,linkedEmail:e.email&&String(e.email).trim()?String(e.email).trim():"",schedule:{timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",blocks:[{days:["mon","tue","wed","thu","fri"],startTime:"09:00",endTime:"17:00"}]}}]}),G(e=>e+1)},[ne,R.liveRequestTeamMembers]),ae=(e,t)=>{ne({liveRequestTeamMembers:(R.liveRequestTeamMembers||[]).map(n=>n.id===e?(0,r.A)((0,r.A)({},n),t):n)})},ie=(e,t,n)=>{ne({liveRequestTeamMembers:(R.liveRequestTeamMembers||[]).map(o=>{var a;if(o.id!==e)return o;const i=[...(null===(a=o.schedule)||void 0===a?void 0:a.blocks)||[]];return i[t]=(0,r.A)((0,r.A)({},i[t]),n),(0,r.A)((0,r.A)({},o),{},{schedule:(0,r.A)((0,r.A)({},o.schedule||{}),{},{blocks:i})})})})},se=new Set((R.liveRequestTeamMembers||[]).map(e=>
1e.userId).filter(Boolean).map(String)),le=U.filter(e=>e.id&&!se.has(String(e.id)));return(0,g.jsxs)("div",{children:[k&&(0,g.jsx)("h4",{className:"text-lg font-medium text-gray-900 mb-4",children:"Live Chat"}),(0,g.jsxs)("div",{className:"space-y-4",children:[j?(0,g.jsx)("p",{className:"text-xs text-gray-500",children:j}):null,!D&&!O&&(0,g.jsxs)("label",{className:"flex items-start",children:[(0,g.jsx)("input",{type:"checkbox",checked:!!R.liveRequestsEmbedEnabled,onChange:e=>ne({liveRequestsEmbedEnabled:e.target.checked}),disabled:x,className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500 mt-0.5"}),(0,g.jsxs)("div",{className:"ml-2",children:[(0,g.jsx)("span",{className:"text-sm text-gray-700 font-medium",children:"Embed & website widget"}),(0,g.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:'Show "Speak to our team" in the embedded agent on your site.'})]})]}),!D&&!(O&&E)&&(0,g.jsxs)("label",{className:"flex items-start",children:[(0,g.jsx)("input",{type:"checkbox",checked:!!R.liveRequestsShareLinkEnabled,onChange:e=>ne({liveRequestsShareLinkEnabled:e.target.checked}),disabled:x,className:"rounded border-gray-300 text-blue-600 focus:ring-blue-500 mt-0.5"}),(0,g.jsxs)("div",{className:"ml-2",children:[(0,g.jsx)("span",{className:"text-sm text-gray-700 font-medium",children:"Shared workspace links"}),(0,g.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Show live handoff when visitors use the AI assistant on a shared link (if the assistant is enabled on that link)."})]})]}),re&&(0,g.jsxs)(g.Fragment,{children:[(0,g.jsx)("div",{className:"space-y-3",children:(0,g.jsx)(c.C,{channels:R.liveRequestNotifyChannels||[],onToggle:e=>{const t=R.liveRequestNotifyChannels||[],n=t.includes(e)?t.filter(t=>t!==e):[...t,e];ne({liveRequestNotifyChannels:n})},disabled:x})}),(0,g.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[(0,g.jsxs)("div",{children:[(0,g.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Capsule button label"}),(0,g.jsx)("input",{type:"text",value:R.liveRequestCapsuleLabel||"",onChange:e=>ne({liveRequestCapsuleLabel:e.target.value}),disabled:x,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Offline message"}),(0,g.jsx)("input",{type:"text",value:R.liveRequestOfflineMessage||"",onChange:e=>ne({liveRequestOfflineMessage:e.target.value}),disabled:x,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Welcome message (when someone is available)"}),(0,g.jsx)("textarea",{rows:2,value:R.liveRequestWelcomeMessage||"",onChange:e=>ne({liveRequestWelcomeMessage:e.target.value}),placeholder:"A specialist will join this chat shortly\u2026",disabled:x,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm"})]}),(0,g.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,g.jsxs)("label",{className:"flex items-center gap-2 text-sm",children:[(0,g.jsx)("input",{type:"checkbox",checked:!1!==R.liveRequestAutoResolveEnabled,onChange:e=>ne({liveRequestAutoResolveEnabled:e.target.checked}),disabled:x,className:"rounded border-gray-300 text-blue-600"}),"Auto-close unanswered live requests"]}),(0,g.jsxs)("div",{className:"flex items-center gap-2",children:[(0,g.jsx)("span",{className:"text-sm text-gray-600",children:"After"}),(0,g.jsx)("input",{type:"number",min:5,max:240,value:R.liveRequestAutoResolveMinutes||3,onChange:e=>ne({liveRequestAutoResolveMinutes:parseInt(e.target.value,10)||3}),disabled:x,className:"w-20 px-2 py-1 border border-gray-300 rounded-md text-sm"}),(0,g.jsx)("span",{className:"text-sm text-gray-600",children:"minutes"})]})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("div",{className:"flex items-center justify-between mb-2",children:(0,g.jsx)("span",{className:"text-sm font-medium text-gray-700",children:"Team members"})}),(0,g.jsx)("p",{className:"text-xs text-gray-500 mb-3",children:"Each member can have their own hours. Empty schedule = always available. Add people from your organization; names and photos can be customized below for the chat widget."}),T?(0,g.jsxs)("div",{className:"mb-4 space-y-2",children:[(0,g.jsx)("label",{className:"block text-xs font-medium text-gray-600",children:"Add from organization"}),(0,g.jsxs)("select",{defaultValue:"",onChange:async e=>{const t=e.target.value;if(!t||!T)return;const n=U.find(e=>String(e.id)===String(t));if(e.target.value="",!n)return;if((R.liveRequestTeamMembers||[]).some(e=>e.userId&&String(e.userId)===String(n.id)))return d.Ay.error("This person is already a live chat team member."),void G(e=>e+1);if(!f(n,T))return Z({member:n}),void G(e=>e+1);await oe(n)},disabled:x||W,className:"w-full px-3 py-2 border border-gray-300 rounded-md text-sm bg-white",children:[(0,g.jsx)("option",{value:"",children:W?"Loading members\u2026":"Select organization member\u2026"}),le.map(e=>{const t=f(e,T),n="".concat(e.name||"Unknown").concat(e.email?" (".concat(e.email,")"):"").concat(t?"":" \u2014 not in this workspace");return(0,g.jsx)("option",{value:e.id,children:n}
1,e.id)})]},H),(0,g.jsx)("button",{type:"button",onClick:()=>F("/invite"),disabled:x,className:"text-sm text-blue-600 hover:text-blue-800 disabled:opacity-50",children:"Invite user to organization\u2026"})]}):(0,g.jsx)("p",{className:"text-xs text-amber-700 mb-3",children:"Workspace context is required to add team members from your organization."}),(0,g.jsx)("div",{className:"space-y-4",children:(R.liveRequestTeamMembers||[]).map(e=>{var t,n;return(0,g.jsxs)("div",{className:"border border-gray-200 rounded-lg p-4 bg-gray-50 space-y-3",children:[(0,g.jsxs)("div",{className:"flex justify-between items-start gap-2",children:[(0,g.jsxs)("div",{className:"flex-1 space-y-2 min-w-0",children:[(0,g.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[(0,g.jsx)("input",{placeholder:"Name (shown in chat)",value:e.name||"",onChange:t=>ae(e.id,{name:t.target.value}),disabled:x,className:"px-3 py-2 border border-gray-300 rounded-md text-sm"}),(0,g.jsx)("input",{placeholder:"Role (optional)",value:e.role||"",onChange:t=>ae(e.id,{role:t.target.value}),disabled:x,className:"px-3 py-2 border border-gray-300 rounded-md text-sm"}),(0,g.jsx)("input",{placeholder:"Staff email (optional, match sign-in)",type:"email",value:e.linkedEmail||"",onChange:t=>ae(e.id,{linkedEmail:t.target.value}),disabled:x,className:"px-3 py-2 border border-gray-300 rounded-md text-sm md:col-span-2"})]}),e.userId?(0,g.jsx)("p",{className:"text-xs text-emerald-700",children:"Linked to workspace account"}):null]}),(0,g.jsx)("button",{type:"button",onClick:()=>{return t=e.id,void ne({liveRequestTeamMembers:(R.liveRequestTeamMembers||[]).filter(e=>e.id!==t)});var t},disabled:x,className:"text-red-600 text-sm shrink-0 disabled:opacity-50",children:"Remove"})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("label",{className:"text-xs text-gray-600",children:"Photo"}),(0,g.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[e.avatarUrl?(0,g.jsx)("img",{src:e.avatarUrl,alt:"",className:"w-10 h-10 rounded-full object-cover border border-gray-200"}):(0,g.jsx)("div",{className:"w-10 h-10 rounded-full bg-gray-200"}),(0,g.jsx)("input",{type:"file",accept:"image/*",disabled:x||!b,onChange:t=>{var n;const r=null===(n=t.target.files)||void 0===n?void 0:n[0];r&&b&&b(e.id,r)},className:"text-sm"})]})]}),(0,g.jsxs)("div",{children:[(0,g.jsx)("label",{className:"text-xs text-gray-600",children:"Timezone"}),(0,g.jsx)("input",{type:"text",value:(null===(t=e.schedule)||void 0===t?void 0:t.timezone)||Intl.DateTimeFormat().resolvedOptions().timeZone,onChange:t=>{var n;return ae(e.id,{schedule:(0,r.A)((0,r.A)({},e.schedule||{}),{},{timezone:t.target.value,blocks:(null===(n=e.schedule)||void 0===n?void 0:n.blocks)||[{days:["mon","tue","wed","thu","fri"],startTime:"09:00",endTime:"17:00"}]})})},disabled:x,className:"mt-1 w-full px-3 py-2 border border-gray-300 rounded-md text-sm",placeholder:"America/New_York"})]}),(0,g.jsxs)("div",{className:"space-y-2",children:[(0,g.jsx)("span",{className:"text-xs font-medium text-gray-600",children:"Availability blocks"}),((null===(n=e.schedule)||void 0===n?void 0:n.blocks)||[{days:["mon","tue","wed","thu","fri"],startTime:"09:00",endTime:"17:00"}]).map((t,n)=>(0,g.jsxs)("div",{className:"flex flex-wrap items-center gap-2 bg-white p-2 rounded border border-gray-100",children:[(0,g.jsx)("div",{className:"flex flex-wrap gap-1",children:h.map(r=>(0,g.jsx)("button",{type:"button",disabled:x,onClick:()=>{const o=t.days||[],a=o.includes(r.id)?o.filter(e=>e!==r.id):[...o,r.id];ie(e.id,n,{days:a})},className:"px-2 py-0.5 rounded text-xs ".concat((t.days||[]).includes(r.id)?"bg-blue-600 text-white":"bg-gray-100 text-gray-600"," ").concat(x?"opacity-50":""),children:r.label},r.id))}),(0,g.jsx)("input",{type:"time",value:t.startTime||"09:00",onChange:t=>ie(e.id,n,{startTime:t.target.value}),disabled:x,className:"text-sm border rounded px-1"}),(0,g.jsx)("span",{className:"text-xs text-gray-500",children:"to"}),(0,g.jsx)("input",{type:"time",value:t.endTime||"17:00",onChange:t=>ie(e.id,n,{endTime:t.target.value}),disabled:x,className:"text-sm border rounded px-1"})]},n)),(0,g.jsx)("button",{type:"button",onClick:()=>{return t=e.id,void ne({liveRequestTeamMembers:(R.liveRequestTeamMembers||[]).map(e=>{var n;if(e.id!==t)return e;const o=[...(null===(n=e.schedule)||void 0===n?void 0:n.blocks)||[],{days:["mon","tue","wed","thu","fri"],startTime:"09:00",endTime:"17:00"}];return(0,r.A)((0,r.A)({},e),{},{schedule:(0,r.A)((0,r.A)({},e.schedule||{}),{},{blocks:o})})})});var t},disabled:x,className:"text-xs text-blue-600 disabled:opacity-50",children:"+ Add hours block"})]})]},e.id)})})]})]})]}),null!==Y&&void 0!==Y&&Y.member?(0,g.jsx)("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/40 p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-invite-title",children:(0,g.jsxs)("div",{className:"bg-white rounded-lg shadow-xl max-w-md w-full p-5 space-y-4",children:[(0,g.jsx)("h3",{id:"workspace-invite-title",className:"text-base font-semibold text-gray-900",children:"Add to workspace?"}),(0,g.jsxs)("p",{className:"text-sm text-gray-700",children:[(0,g.jsx)("strong",{children:Y.member.name||"This user"})," is not a member of this workspace. Adding them as a live chat team member will also grant them ",(0,g.jsx)("strong",{children:"viewer"})," access to this workspace. Continue?"]}),(0,g.jsxs)("div",{className:"flex justify-end gap-2 pt-2",children:[(0,g.jsx)("button",{type:"button",className:"px-3 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50",disabled:ee,onClick:()=>{Z(null),G(e=>e+1)},children:"Cancel"}),(0,g.jsx)("button",{type:"button",className:"px-3 py-2 text-sm rounded-md bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50",disabled:ee,onClick:async()=>
1{if(null===Y||void 0===Y||!Y.member||!T)return;const e=Y.member;te(!0);try{await(0,m.aI)(T,e.id,"viewer"),d.Ay.success("".concat(e.name||"User"," can now access this workspace.")),Z(null),await oe(e)}catch(t){console.error("updateUserWorkspaceRole",t),d.Ay.error((null===t||void 0===t?void 0:t.message)||"Could not add user to workspace")}finally{te(!1)}},children:ee?"Adding\u2026":"Continue"})]})]})}):null]})}},13471(e,t,n){n.d(t,{C:()=>m,w:()=>c});var r=n(5544),o=n(65043),a=n(52395),i=n(92339),s=n(96822),l=n(70579);const d=(0,a.httpsCallable)(s.Cn,"sendTestPushNotification"),c="https://apps.apple.com/us/app/based-small-business-os/id6748622975",u=["email","chatInsights","app"];function m(e){let t=e.channels,n=void 0===t?[]:t,a=e.onToggle,s=e.disabled,m=void 0!==s&&s;const p=Array.isArray(n)?n:[],g=(0,o.useState)(!1),h=(0,r.A)(g,2),f=h[0],y=h[1],v=(0,o.useCallback)(async()=>{y(!0);try{const e=(await d()).data;null!==e&&void 0!==e&&e.success?i.Ay.success("Test push sent. Check your device."):i.Ay.error("string"===typeof(null===e||void 0===e?void 0:e.detail)&&e.detail?e.detail:"no_tokens"===(null===e||void 0===e?void 0:e.reason)||"no_valid_tokens"===(null===e||void 0===e?void 0:e.reason)?"Sign in on the Based app on your phone so it can register for push, then try again.":"Could not send test push.")}catch(e){i.Ay.error((null===e||void 0===e?void 0:e.message)||"Failed to send test push")}finally{y(!1)}},[]);return(0,l.jsxs)(l.Fragment,{children:[(0,l.jsxs)("div",{children:[(0,l.jsx)("p",{className:"text-sm font-medium text-gray-700 mb-2",children:"Notify me via"}),(0,l.jsx)("div",{className:"flex flex-wrap gap-1",children:u.map(e=>(0,l.jsxs)("label",{className:"inline-flex items-center gap-1 px-2 py-1.5 rounded border border-gray-200 text-sm ".concat(m?"opacity-60 cursor-not-allowed":"cursor-pointer"),children:[(0,l.jsx)("input",{type:"checkbox",checked:p.includes(e),onChange:()=>!m&&(null===a||void 0===a?void 0:a(e)),disabled:m,className:"rounded border-gray-300 text-blue-600"}),(0,l.jsx)("span",{children:"email"===e?"Email":"chatInsights"===e?"Chat Inbox":"App"})]},e))}),(0,l.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:"Email sends an urgent alert. Chat Inbox is the inbox in Based. App allows you to receive push notifications and reply on the go."})]}),p.includes("app")&&(0,l.jsxs)("div",{className:"rounded-lg border border-blue-200 bg-blue-50 px-3 py-2.5 text-sm text-blue-900",children:[(0,l.jsx)("p",{className:"text-xs leading-relaxed",children:"Install the Based app on your phone to get live push notifications and reply on the go. Urgent emails also include a link to get the app."}),(0,l.jsxs)("div",{className:"mt-2 flex flex-wrap items-center gap-3",children:[(0,l.jsx)("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-sm font-medium text-blue-700 underline hover:text-blue-800",children:"Get the app"}),(0,l.jsx)("button",{type:"button",onClick:v,disabled:m||f,className:"text-sm font-medium text-blue-800 bg-white border border-blue-200 rounded px-2.5 py-1 hover:bg-blue-100 disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Sending\u2026":"Send test push"})]}),(0,l.jsx)("p",{className:"text-xs text-blue-800/80 mt-2",children:"Sends a test notification to devices where you are signed in to the Based app (same account as here)."})]})]})}},82665(e,t,n){n.d(t,{Hp:()=>h,OZ:()=>d,Uo:()=>p,oN:()=>g});const r="Welcome to Based!";function o(e){return{type:"text",text:e,marks:arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]}}function a(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return{type:"paragraph",content:t}}function i(e,t){return{type:"heading",attrs:{level:e},content:[o(t)]}}function s(e){return{type:"listItem",content:[a(o(e))]}}function l(e){return{type:"listItem",content:[a(...e)]}}function d(){return"https://images.pexels.com/photos/7281926/pexels-photo-7281926.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=1200"}function c(e){return{type:"doc",content:[i(1,r),a(o("Based is a smart knowledge management platform that helps you organize, share, and interact with your documents using AI. Whether you're building a company wiki, creating training materials, or managing internal documentation, Based makes it simple.")),i(2,"What you can do with Based"),{type:"bulletList",content:[s("Create and organize documents \u2014 Write rich-text documents and group them into workspaces (projects)."),s("Ask the AI Assistant \u2014 Chat with an AI that understands your documents and can answer questions about them."),s("Share with anyone \u2014 Generate public links to share your workspace or individual documents with people outside your team."),s("Embed on your website \u2014 Add an AI chatbot or FAQ widget to your own site, powered by your Based documents."),s("Collaborate with your team \u2014 Invite team members, assign roles, and work together in real time."),s("Integrations on your documents \u2014 Embed forms, add document signatures, and connect Stripe for payments and invoicing when your organization enables them in Based Abilities.")]},i(2,"Get started in your workspace"),a(o("You already have a Default Workspace. Here are a few quick steps:")),{type:"orderedList",content:[l([o("Explore this document",[{type:"bold"}
1]),o(" \u2014 Click anywhere to edit and try the editor.")]),l([o("Create another document",[{type:"bold"}]),o(" \u2014 Use the + control in the sidebar to add a document.")]),l([o("Explore Based Abilities",[{type:"bold"}]),o(" \u2014 From your profile menu, open Based Abilities to enable forms, document signatures, and Stripe for payments and invoicing.")]),l([o("Open the AI Assistant",[{type:"bold"}]),o(" \u2014 Ask questions about your documents.")]),l([o("Try a public link",[{type:"bold"}]),o(" \u2014 When you're ready, share a workspace or document from the sharing options.")])]},a(o("Based Abilities let you extend what the AI can do with your knowledge base \u2014 explore them from the product when you're ready.")),i(2,"Security & privacy"),a(o("Your documents are encrypted in transit and at rest. Only you and people you invite can access your organization's content.")),i(2,"Need help?"),a(o("Visit the Based Help Center for full guides on every feature: "),o(e,[{type:"link",attrs:{href:e,target:"_blank",rel:"noopener noreferrer nofollow"}}])),a(o("Happy knowledge building!",[{type:"bold"}])),a(o("This document was automatically created to help you get started. Feel free to edit, expand, or delete it as needed!",[{type:"italic"}]))]}}function u(e){return"".concat(r,"\n\nBased is a smart knowledge management platform that helps you organize, share, and interact with your documents using AI. Whether you're building a company wiki, creating training materials, or managing internal documentation, Based makes it simple.\n\nWhat you can do with Based\n\n\u2022 Create and organize documents \u2014 Write rich-text documents and group them into workspaces (projects).\n\u2022 Ask the AI Assistant \u2014 Chat with an AI that understands your documents and can answer questions about them.\n\u2022 Share with anyone \u2014 Generate public links to share your workspace or individual documents with people outside your team.\n\u2022 Embed on your website \u2014 Add an AI chatbot or FAQ widget to your own site, powered by your Based documents.\n\u2022 Collaborate with your team \u2014 Invite team members, assign roles, and work together in real time.\n\u2022 Integrations on your documents \u2014 Embed forms, add document signatures, and connect Stripe for payments and invoicing when your organization enables them in Based Abilities.\n\nGet started in your workspace\n\nYou already have a Default Workspace. Here are a few quick steps:\n\n1. Explore this document \u2014 Click anywhere to edit and try the editor.\n2. Create another document \u2014 Use the + control in the sidebar to add a document.\n3. Explore Based Abilities \u2014 From your profile menu, open Based Abilities to enable forms, document signatures, and Stripe for payments and invoicing.\n4. Open the AI Assistant \u2014 Ask questions about your documents.\n5. Try a public link \u2014 When you're ready, share a workspace or document from the sharing options.\n\nBased Abilities let you extend what the AI can do with your knowledge base \u2014 explore them from the product when you're ready.\n\nSecurity & privacy\n\nYour documents are encrypted in transit and at rest. Only you and people you invite can access your organization's content.\n\nNeed help?\n\nVisit the Based Help Center: ").concat(e,"\n\nHappy knowledge building!\n\nThis document was automatically created to help you get started. Feel free to edit, expand, or delete it as needed!")}function m(e){const t=e.replace(/&/g,"&amp;").replace(/"/g,"&quot;");return"<h1>".concat(r,"</h1>\n<p>Based is a smart knowledge management platform that helps you organize, share, and interact with your documents using AI. Whether you're building a company wiki, creating training materials, or managing internal documentation, Based makes it simple.</p>\n<h2>What you can do with Based</h2>\n<ul>\n<li><p>Create and organize documents \u2014 Write rich-text documents and group them into workspaces (projects).</p></li>\n<li><p>Ask the AI Assistant \u2014 Chat with an AI that understands your documents and can answer questions about them.</p></li>\n<li><p>Share with anyone \u2014 Generate public links to share your workspace or individual documents with people outside your team.</p></li>\n<li><p>Embed on your website \u2014 Add an AI chatbot or FAQ widget to your own site, powered by your Based documents.</p></li>\n<li><p>Collaborate with your team \u2014 Invite team members, assign roles, and work together in real time.</p></li>\n<li><p>Integrations on your documents \u2014 Embed forms, add document signatures, and connect Stripe for payments and invoicing when your organization enables them in Based Abilities.</p></li>\n</ul>\n<h2>Get started in your workspace</h2>\n<p>You already have a Default Workspace. Here are a few quick steps:</p>\n<ol>\n<li><p><strong>Explore this document</strong>
1 \u2014 Click anywhere to edit and try the editor.</p></li>\n<li><p><strong>Create another document</strong> \u2014 Use the + control in the sidebar to add a document.</p></li>\n<li><p><strong>Explore Based Abilities</strong> \u2014 From your profile menu, open Based Abilities to enable forms, document signatures, and Stripe for payments and invoicing.</p></li>\n<li><p><strong>Open the AI Assistant</strong> \u2014 Ask questions about your documents.</p></li>\n<li><p><strong>Try a public link</strong> \u2014 When you're ready, share a workspace or document from the sharing options.</p></li>\n</ol>\n<p>Based Abilities let you extend what the AI can do with your knowledge base \u2014 explore them from the product when you're ready.</p>\n<h2>Security &amp; privacy</h2>\n<p>Your documents are encrypted in transit and at rest. Only you and people you invite can access your organization's content.</p>\n<h2>Need help?</h2>\n<p>Visit the Based Help Center for full guides on every feature: <a href=\"").concat(t,'" target="_blank" rel="noopener noreferrer nofollow">').concat(e.replace(/&/g,"&amp;").replace(/</g,"&lt;"),"</a></p>\n<p><strong>Happy knowledge building!</strong></p>\n<p><em>This document was automatically created to help you get started. Feel free to edit, expand, or delete it as needed!</em></p>")}function p(e){const t=e||{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_VERCEL_GIT_COMMIT_AUTHOR_NAME:"Gary Riger",REACT_APP_VERCEL_GIT_PROVIDER:"github",REACT_APP_VERCEL_PROJECT_ID:"prj_A5c8ZMv75ibxQVceA3I7GjPny9oD",REACT_APP_VERCEL_GIT_PULL_REQUEST_ID:"",REACT_APP_VERCEL_OBSERVABILITY_CLIENT_CONFIG:'{"analytics":{"scriptSrc":"8f81e36d25c71756/script.js","viewEndpoint":"8f81e36d25c71756/view","eventEndpoint":"8f81e36d25c71756/event","sessionEndpoint":"8f81e36d25c71756/session"},"speedInsights":{"scriptSrc":"1e9f61cb490e195d/script.js","endpoint":"1e9f61cb490e195d/vitals"}}',REACT_APP_VERCEL_BRANCH_URL:"based-git-main-trybased.vercel.app",REACT_APP_VERCEL_GIT_COMMIT_MESSAGE:"Merge pull request #69 from grigerny/cursor/native-document-tables-6648\n\nNative document tables for editor and MCP agents",REACT_APP_VERCEL_DEPLOYMENT_ID:"dpl_6MQChUZTeZEjuh9PAEPmwanHsu8y",REACT_APP_VERCEL_GIT_REPO_SLUG:"knowledge-base-saas",REACT_APP_VERCEL_TARGET_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_SHA:"fe8e0cad17d5c751081fbff8964f57a16f15178c",REACT_APP_VERCEL_ENV:"production",REACT_APP_VERCEL_GIT_COMMIT_REF:"main",REACT_APP_VERCEL_URL:"based-o7e1bdtta-trybased.vercel.app",REACT_APP_VERCEL_PROJECT_PRODUCTION_URL:"www.trybased.com",REACT_APP_VERCEL_GIT_PREVIOUS_SHA:"",REACT_APP_VERCEL_GIT_REPO_ID:"980833582",REACT_APP_VERCEL_GIT_COMMIT_AUTHOR_LOGIN:"grigerny",REACT_APP_VERCEL_GIT_REPO_OWNER:"grigerny"}.REACT_APP_HELP_CENTER_URL||"https://trybased.com/shared/based-help-center";return{editorJson:c(t),textContent:u(t),editorHtml:m(t)}}const g=r;function h(){return{summary:"Get started with Based: workspaces, AI Assistant, sharing, embeddable widgets, integrations (forms, signatures, Stripe), and Based Abilities.",keyElements:["getting started","workspaces","AI Assistant","sharing","embedding","integrations","forms","signatures","Stripe","Based Abilities","encryption"],relatedTopics:["documentation","help center","onboarding","collaboration"]}}},8535(e,t,n){n.d(t,{$2:()=>o,IE:()=>d,J$:()=>h,Q4:()=>p,U:()=>g,W_:()=>a,Wy:()=>u,cF:()=>i,x7:()=>m,z1:()=>r});const r="ai-category-updated",o=20,a=4500,i=3,s=/^(Untitled Document|Untitled)\b/i,l=new Set(["","uncategorized","general"]);function d(e){return l.has(String(e||"").trim().toLowerCase())}function c(e){let t=String(e||"").replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return t=t.replace(s,"").replace(/\s+/g," ").trim(),s.test(t)||""===t?"":t}function u(e){return c(e).length>=12}function m(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if("pdf"===(null===t||void 0===t?void 0:t.viewerMode))return!1;const n=String((null===t||void 0===t?void 0:t.title)||"").trim();if(n&&"Untitled Document"!==n&&"Untitled"!==n)return!1;const r=c(function(e){let t=e;if("string"===typeof t)try{t=JSON.parse(t)}catch(o){return""}if(!t||"object"!==typeof t)return"";const n=[],r=e=>{e&&"object"===typeof e&&("text"===e.type&&"string"===typeof e.text&&n.push(e.text),Array.isArray(e.content)&&e.content.forEach(r))};return r(t),n.join(" ").replace(/\s+/g," ").trim()}(e));if(r)return!1;return!c((null===t||void 0===t?void 0:t.textContent)||(null===t||void 0===t?void 0:t.editorHtml)||"")}function p(e,t){const n=String(e||"").trim();if(n&&"Untitled Document"!==n&&"Untitled"!==n)return n.slice(0,200);return String(t||"").replace(/<[^>]*>/g,"").trim().slice(0,200)}function g(e){if(null===e||void 0===e||!e.id)return!1;if(e.isNew||String(e.id).startsWith("new_"))return!1;if(e.coverImageUrl)return!1;if("image"===e.type||e.fileType&&String(e.fileType).startsWith("image/"))return!1;if("pdf"===e.viewerMode)return!1;const t=e.editorHtml||(e.textContent&&"[Encrypted Content]"!==e.textContent?e.textContent:"");return p(e.title,t).length>=i}function h(e){if(!e)return"";const t=e.editorHtml||(e.textContent&&"[Encrypted Content]"!==e.textContent?e.textContent:"");return p(e.title,t)}},20438(e,t,n){n.d(t,{d:()=>s,recordDocCreatedEvent:()=>i});var r=n(52395),o=n(1862);function a(){return(0,r.getFunctions)(void 0,"us-central1")}async function i(e){if(e&&"string"===typeof e)try{const t=(0,r.httpsCallable)(a(),"recordDocCreated"),n=await t({docId:e});
1(0,o.gg)("[accountMetrics] recordDocCreated",n.data)}catch(t){(0,o.gg)("[accountMetrics] recordDocCreated failed",(null===t||void 0===t?void 0:t.message)||t)}}async function s(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.sessionId,n=e.docId,i=e.durationSeconds,s=e.scrollDepthPct;if(!t||!n)return null;try{const e=(0,r.httpsCallable)(a(),"recordInAppDocView");return(await e({sessionId:t,docId:n,durationSeconds:Math.max(0,Math.floor(Number(i)||0)),scrollDepthPct:Math.max(0,Math.min(100,Math.floor(Number(s)||0)))})).data||null}catch(l){return(0,o.gg)("[accountMetrics] recordInAppDocView failed",(null===l||void 0===l?void 0:l.message)||l),null}}},60626(e,t,n){n.d(t,{d:()=>r});n(52395),n(1862);function r(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:5;const n=[],r=e=>{var t;"image"===(null===e||void 0===e?void 0:e.type)&&null!==e&&void 0!==e&&null!==(t=e.attrs)&&void 0!==t&&t.src&&n.push(e.attrs.src),null!==e&&void 0!==e&&e.content&&Array.isArray(e.content)&&e.content.forEach(r)};return null!==e&&void 0!==e&&e.content&&e.content.forEach(r),n.slice(0,t)}},12764(e,t,n){n.d(t,{V:()=>s});var r=n(1862),o=n(52395);const a=(0,o.getFunctions)(),i=(0,o.httpsCallable)(a,"generateCategory");async function s(e){if(!e||"string"!==typeof e||0===e.trim().length)return(0,r.gg)("\u26a0\ufe0f generateCategoryFromContent: Invalid content provided"),null;try{const t=(await i({content:e})).data;return t&&"string"===typeof t.category?((0,r.gg)("\u2705 Category generated successfully:",t.category,t.subcategory),{category:t.category,subcategory:"string"===typeof t.subcategory?t.subcategory:"General"}):((0,r.gg)("\u26a0\ufe0f generateCategoryFromContent: No category returned from function"),null)}catch(t){return(0,r.gg)("\u26a0\ufe0f Error generating category:",t.message||t.code||"Unknown error"),null}}},17412(e,t,n){n.d(t,{S:()=>a});var r=n(52395);const o={versionControl:"enableVersionControlIntegration",timer:"enableTimerIntegration",cursorDevSync:"enableCursorDevSyncIntegration",pdfExport:"enablePdfExportIntegration",documentSignatures:"enableDocumentSignaturesIntegration",documentLock:"enableDocumentLockIntegration",autoTitle:"enableAutoTitleIntegration",autoCategory:"enableAutoCategoryIntegration",sopEnhancement:"enableSopEnhancementIntegration",voice:"enableVoiceIntegration",pexels:"enablePexelsIntegration",forms:"enableFormsIntegration",templateFill:"enableTemplateFillIntegration",envVault:"enableEnvVaultIntegration"};async function a(e,t){if(!e)return{ok:!1,errorMessage:"No organization selected."};if("stripe"===t)return{ok:!1,errorMessage:"Connect Stripe from Integrations to accept payments."};const n=o[t];if(!n)return{ok:!1,errorMessage:"This ability cannot be turned on from here."};try{var a;const t=(0,r.httpsCallable)((0,r.getFunctions)(),n);return null!==(a=(await t({organizationId:e})).data)&&void 0!==a&&a.success?{ok:!0}:{ok:!1,errorMessage:"Could not enable this ability. Try Integrations in Settings."}}catch(i){const e=(null===i||void 0===i?void 0:i.message)||(null===i||void 0===i?void 0:i.details)||"Failed to enable";return console.error("enableCreateWithAIIntegration:",t,i),{ok:!1,errorMessage:e}}}},18303(e,t,n){n.d(t,{Aj:()=>c,gP:()=>m,setCurrentVersion:()=>p,x1:()=>u});var r=n(89379),o=n(55472),a=n(96822),i=n(1862),s=n(12947);function l(e){return"string"===typeof e?e:null}function d(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return null==e||function(e){return null!=e&&"object"===typeof e&&"string"===typeof e._methodName}(e)?t:e}const c=async function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{if(!e)throw new Error("Document ID is required");let x="";const b=t.editorHtml;if("string"===typeof b&&b.trim())x=b.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim();else if("string"===typeof t.editorJson||"object"===typeof t.editorJson&&null!==t.editorJson&&"type"in t.editorJson){const e=t=>t&&"object"===typeof t?"text"===t.type&&t.text?t.text:t.content&&Array.isArray(t.content)?t.content.map(e).join(" ").trim():"":"";if("string"===typeof t.editorJson)try{const n=JSON.parse(t.editorJson);x=e(n)}catch(v){x=e(t.editorJson)}else x=e(t.editorJson)}!x&&t.textContent&&"[Encrypted Content]"!==t.textContent&&(x=t.textContent),x.length>200&&(x=x.substring(0,200)+"...");const w=(0,r.A)((0,r.A)((0,r.A)({editorJson:l(t.editorJson),editorHtml:l(t.editorHtml),title:d(t.title,"")||"Untitled",textContent:d(t.textContent,"")||"",previewText:x||("string"===typeof t.title?t.title:"")||"No preview available",isEncrypted:Bo
1olean(d(t.isEncrypted,!1)),encryptedResult:d(t.encryptedResult),userEncryptedResult:d(t.userEncryptedResult),workspaceEncryptedResults:d(t.workspaceEncryptedResults),encryptionMethod:d(t.encryptionMethod),category:d(t.category,"")||"",workspace:d(t.workspace,"")||"Default",workspaceIds:Array.isArray(t.workspaceIds)?t.workspaceIds:[]},d(t.documentKind)?{documentKind:d(t.documentKind)}:{}),d(t.envConfigMeta)?{envConfigMeta:d(t.envConfigMeta)}:{}),{},{createdAt:(0,o.O5)(),createdBy:t.userId||null,versionNumber:null,isCurrent:!1,description:n.description||null});if(w.isEncrypted){w.editorJson||w.editorHtml||w.textContent&&"[Encrypted Content]"!==w.textContent?(0,i.gg)("\u2705 Encrypted document version has decrypted content for comparison:",{hasEditorJson:!!w.editorJson,hasEditorHtml:!!w.editorHtml,hasTextContent:!(!w.textContent||"[Encrypted Content]"===w.textContent)}):(console.warn("\u26a0\ufe0f WARNING: Creating version for encrypted document ".concat(e," without decrypted content!"),{hasEditorJson:!!w.editorJson,hasEditorHtml:!!w.editorHtml,hasTextContent:!!w.textContent,textContentValue:w.textContent}),(0,i.gg)("\u26a0\ufe0f Encrypted document version missing decrypted content - version comparison may not work correctly"))}const k=(0,o.rJ)(a.db,"knowledgeBaseDocuments",e,"versions"),A=(0,o.P)(k,(0,o.My)("createdAt","desc"),(0,o.AB)(1)),j=await(0,o.GG)(A),N=!1!==(null===n||void 0===n?void 0:n.forceVersion);if(!N&&j.size>0){var c,u;const t=j.docs[0].data();(0,i.gg)("\ud83d\udd0d Comparing new version with most recent version for document ".concat(e,":"),{isEncrypted:w.isEncrypted,mostRecentIsEncrypted:t.isEncrypted,hasNewEditorJson:!!w.editorJson,hasOldEditorJson:!!t.editorJson,hasNewEditorHtml:!!w.editorHtml,hasOldEditorHtml:!!t.editorHtml,hasNewTextContent:!(!w.textContent||"[Encrypted Content]"===w.textContent),hasOldTextContent:!(!t.textContent||"[Encrypted Content]"===t.textContent)});let n=null,r=null,o=null;if(w.editorJson?(o="editorJson",n="string"===typeof w.editorJson?w.editorJson:JSON.stringify(w.editorJson),r=t.editorJson?"string"===typeof t.editorJson?t.editorJson:JSON.stringify(t.editorJson):null):w.editorHtml?(o="editorHtml",n=w.editorHtml,r=t.editorHtml||null):w.textContent&&"[Encrypted Content]"!==w.textContent&&(o="textContent",n=w.textContent,r=t.textContent&&"[Encrypted Content]"!==t.textContent?t.textContent:null),(0,i.gg)("\ud83d\udcca Content comparison using method: ".concat(o||"none"),{hasNewContent:!!n,hasOldContent:!!r,newContentLength:(null===(c=n)||void 0===c?void 0:c.length)||0,oldContentLength:(null===(u=r)||void 0===u?void 0:u.length)||0}),n&&r&&n===r)return(0,i.gg)("\u23ed\ufe0f Skipping version creation - content unchanged for document ".concat(e," (compared via ").concat(o,")")),null;if(n&&r&&n!==r?(0,i.gg)("\ud83d\udcdd Content changed detected (".concat(o,") - will create new version")):n&&r||(0,i.gg)("\u26a0\ufe0f Cannot compare content - missing data (new: ".concat(!!n,", old: ").concat(!!r,") - will check encrypted comparison if applicable")),w.isEncrypted&&t.isEncrypted){(0,i.gg)("\ud83d\udd12 Both versions are encrypted - comparing decrypted content for document ".concat(e));let n=null,r=null;if(w.editorJson&&t.editorJson){var m,p;if((0,i.gg)("\ud83d\udd0d Comparing encrypted documents using decrypted editorJson"),n="string"===typeof w.editorJson?w.editorJson:JSON.stringify(w.editorJson),r="string"===typeof t.editorJson?t.editorJson:JSON.stringify(t.editorJson),(0,i.gg)("\ud83d\udcca Decrypted editorJson comparison:",{newLength:(null===(m=n)||void 0===m?void 0:m.length)||0,oldLength:(null===(p=r)||void 0===p?void 0:p.length)||0,areEqual:n===r}),n&&r&&n===r)return(0,i.gg)("\u23ed\ufe0f Skipping version creation - decrypted editorJson unchanged for encrypted document ".concat(e)),null;(0,i.gg)("\ud83d\udcdd Decrypted editorJson differs - will create new version")}else if(w.editorHtml&&t.editorHtml){var g,h;if((0,i.gg)("\ud83d\udd0d Comparing encrypted documents using decrypted editorHtml"),n=w.editorHtml,r=t.editorHtml,(0,i.gg)("\ud83d\udcca Decrypted editorHtml comparison:",{newLength:(null===(g=n)||void 0===g?void 0:g.length)||0,oldLength:(null===(h=r)||void 0===h?void 0:h.length)||0,areEqual:n===r}),n===r)return(0,i.gg)("\u23ed\ufe0f Skipping version creation - decrypted editorHtml unchanged for encrypted document ".concat(e)),null;(0,i.gg)("\ud83d\udcdd Decrypted editorHtml differs - will create new version")}else if(w.textContent&&t.textContent&&"[Encrypted Content]"!==w.textContent&&"[Encrypted Content]"!==t.textContent){var f,y;if((0,i.gg)("\ud83d\udd0d Comparing encrypted documents using decrypted textContent"),n=w.textContent,r=t.textContent,(0,i.gg)("\ud83d\udcca Decrypted textContent comparison:",{newLength:(null===(f=n)||void 0===f?void 0:f.length)||0,oldLength:(null===(y=r)||void 0===y?void 0:y.length)||0,areEqual:n===r}),n===r)return(0,i.gg)("\u23ed\ufe0f Skipping version creation - decrypted textContent unchanged for encrypted document ".concat(e)),null;(0,i.gg)("\ud83d\udcdd Decrypted textContent differs - will create new version")}else console.warn("\u26a0\ufe0f WARNING: Encrypted document version missing decrypted content for comparison:",{documentId:e,hasNewEditorJson:!!w.editorJson,hasOldEditorJson:!!t.editorJson,hasNewEditorHtml:!!w.editorHtml,hasOldEditorHtml:!!t.editorHtml,hasNewTextContent:!!w.textContent,hasOldTextContent:!!t.textContent}),(0,i.gg)("\u26a0\ufe0f Cannot compare decrypted content for encrypted document ".concat(e," - will create version anyway"))}}else N&&(0,i.gg)("\u2705 Force version creation enabled - will create version regardless of content changes");const C=(0,o.P)(k,(0,o.My)("createdAt","desc")),S=(await(0,o.GG)(C)).size+1;w.versionNumber=S;const E=(0,o.doc)(k),I=await(0,s.$X)(w,{docId:e,versionId:E.id,isEncrypted:!!w.isEncrypted,isUpdate:!1});
1return await(0,o.BN)(E,I),(0,i.gg)("\u2705 Created version ".concat(S," for document ").concat(e,":"),E.id),E.id}catch(x){throw console.error("\u274c Error creating document version:",x),x}},u=async function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};try{if(!e)throw new Error("Document ID is required");const n=(0,o.rJ)(a.db,"knowledgeBaseDocuments",e,"versions"),s=t.limit||50,l=[(0,o.My)("createdAt","desc"),...t.startAfterSnapshot?[(0,o.HM)(t.startAfterSnapshot)]:[],(0,o.AB)(s+1)],d=(0,o.P)(n,...l),c=(await(0,o.GG)(d)).docs,u=c.length>s,m=u?c.slice(0,s):c,p=m.map(e=>{var t,n;return(0,r.A)((0,r.A)({id:e.id},e.data()),{},{createdAt:(null===(t=e.data().createdAt)||void 0===t||null===(n=t.toDate)||void 0===n?void 0:n.call(t))||e.data().createdAt||null})}),g=m.length>0?m[m.length-1]:null;return(0,i.gg)("\ud83d\udcda Retrieved ".concat(p.length," versions for document ").concat(e).concat(u?" (more available)":"")),{versions:p,hasMore:u,lastSnapshot:g}}catch(n){throw console.error("\u274c Error fetching document versions:",n),n}},m=async(e,t)=>{try{if(!e||!t)throw new Error("Document ID and Version ID are required");const n=await(async(e,t)=>{try{var n,i;if(!e||!t)throw new Error("Document ID and Version ID are required");const d=(0,o.doc)(a.db,"knowledgeBaseDocuments",e,"versions",t),c=await(0,o.getDoc)(d);if(!c.exists())return null;let u=(0,r.A)((0,r.A)({id:c.id},c.data()),{},{createdAt:(null===(n=c.data().createdAt)||void 0===n||null===(i=n.toDate)||void 0===i?void 0:i.call(n))||c.data().createdAt||null});try{u=await(0,s.fX)(u)}catch(l){console.error("\u274c Failed to hydrate version content from Storage:",{documentId:e,versionId:t,err:l})}return u}catch(d){throw console.error("\u274c Error fetching document version:",d),d}})(e,t);if(!n)throw new Error("Version not found");const l=(0,o.doc)(a.db,"knowledgeBaseDocuments",e),d=await(0,o.getDoc)(l);if(!d.exists())throw new Error("Document not found");const c=d.data(),u={updatedAt:(0,o.O5)(),restoredFromVersion:t,restoredAt:(0,o.O5)()};n.isEncrypted?(n.userEncryptedResult&&(u.userEncryptedResult=n.userEncryptedResult),n.workspaceEncryptedResults&&(u.workspaceEncryptedResults=n.workspaceEncryptedResults),n.encryptedResult&&(u.encryptedResult=n.encryptedResult),u.isEncrypted=!0,n.encryptionMethod&&(u.encryptionMethod=n.encryptionMethod)):(null!==n.editorJson&&void 0!==n.editorJson&&(u.editorJson=n.editorJson),null!==n.editorHtml&&void 0!==n.editorHtml&&(u.editorHtml=n.editorHtml),null!==n.textContent&&void 0!==n.textContent&&(u.textContent=n.textContent),u.isEncrypted=!1),n.title&&(u.title=n.title),null!==n.category&&void 0!==n.category&&(u.category=n.category),n.documentKind&&(u.documentKind=n.documentKind),null!=n.envConfigMeta&&(u.envConfigMeta=n.envConfigMeta),"envVault"!==n.documentKind&&"envVault"!==c.documentKind||(u.documentKind="envVault",u.textContent="[Encrypted Content]",u.excludeFromSearch=!0,u.encryptionMethod=n.encryptionMethod||"user",u.isEncrypted=!0,u.workspaceEncryptedResults=(0,o.CL)(),u.encryptedResult=(0,o.CL)(),u.editorJson=(0,o.CL)(),u.editorHtml=(0,o.CL)()),n.workspaceIds&&Array.isArray(n.workspaceIds)?(u.workspaceIds=n.workspaceIds,n.workspaceIds.length>0&&n.workspaceIds[0]&&(u.workspaceId=n.workspaceIds[0])):c.workspaceIds&&Array.isArray(c.workspaceIds)&&c.workspaceIds.length>0?(u.workspaceIds=c.workspaceIds,u.workspaceId=c.workspaceIds[0]):c.workspaceId&&(u.workspaceId=c.workspaceId,u.workspaceIds||(u.workspaceIds=[c.workspaceId])),c.userId&&(u.userId=c.userId);const m=await(0,s.$X)(u,{docId:e,isEncrypted:!!n.isEncrypted,isUpdate:!0});await(0,o.mZ)(l,m),await p(e,t),(0,i.gg)("\u2705 Restored version ".concat(t," as current for document ").concat(e))}catch(n){throw console.error("\u274c Error restoring document version:",n),n}},p=async(e,t)=>{try{if(!e||!t)throw new Error("Document ID and Version ID are required");const n=(0,o.rJ)(a.db,"knowledgeBaseDocuments",e,"versions"),r=(0,o.P)(n),s=await(0,o.GG)(r),l=[];s.docs.forEach(e=>{e.id!==t&&e.data().isCurrent&&l.push((0,o.mZ)(e.ref,{isCurrent:!1}))});const d=(0,o.doc)(a.db,"knowledgeBaseDocuments",e,"versions",t);l.push((0,o.mZ)(d,{isCurrent:!0})),await Promise.all(l),(0,i.gg)("\u2705 Set version ".concat(t," as current for document ").concat(e))}catch(n){throw console.error("\u274c Error setting current version:",n),n}}},20669(e,t,n){n.d(t,{Be:()=>u,Tj:()=>c});var r=n(89379),o=n(55472),a=n(96822),i=n(96060),s=n(84441),l=(n(12947),n(18303)),d=n(24489);async function c(e){const t=e||{},n=t.userId,l=t.title,d=void 0===l?"Env Vault":l,c=t.workspaceIds,u=void 0===c?[]:c,m=t.folderId,p=void 0===m?null:m;if(!n)throw new Error("userId is required");const g=(0,s.LI)(),h=await(0,i.tE)(JSON.stringify(g),n),f=(0,o.doc)((0,o.rJ)(a.db,"knowledgeBaseDocuments")),y=(0,r.A)((0,r.A)({title:String(d||"Env Vault").trim()||"Env Vault",category:"Secrets",documentKind:s.gV,excludeFromSearch:!0,userId:n,workspaceIds:Array.isArray(u)?u.filter(Boolean):[],workspaceId:Array.isArray(u)&&u[0]?u[0]:null},p?{folderId:p}:{}),{},{isEncrypted:!0,encryptionMethod:"user",userEncryptedResult:h.userEncryptedResult,textContent:"[Encrypted Content]",status:"completed",fileType:"text/plain",fileName:"env-vault.yaml",fileSize:0,coverImageUrl:s.b_,envConfigMeta:(0,s.sh)(g),createdAt:(0,o.O5)(),updatedAt:(0,o.O5)()});return await(0,o.BN)(f,y),{id:f.id}}async function u(e,t,n){let r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(!e||!t)throw new Error("documentId and userId are required");const c=(0,s.rX)(n),u=JSON.stringify(c),m=await(0,i.tE)(u,t),p=(0,s.sh)(c),g=null!=r.title?String(r.title).trim()||"Env Vault":void 0,h={documentKind:s.gV,excludeFromSearch:!0,isEncrypted:!0,encryptionMethod:"user",userEncryptedResult:m.userEncryptedResult,workspaceEncryptedResults:(0,o.CL)(),encryptedResult:(0,o.CL)(),editorJson:(0,o.CL)(),editorHtml:(0,o.CL)(),textContent:"[Encrypted Content]",envConfigMeta:
1p,updatedAt:(0,o.O5)(),status:"completed"};null!=g&&(h.title=g),await(0,o.BN)((0,o.doc)(a.db,"knowledgeBaseDocuments",e),h,{merge:!0});let f=null;const y=await async function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=e.organizationId,n=e.versionControlEnabled;return t?(0,d.DQ)({organizationId:t}):Boolean(n)}(r);if(y)try{let n=g,i=r.category,d=r.workspaceIds,c=r.workspace;if(null==n||null==i||null==d||null==c){const t=await(0,o.getDoc)((0,o.doc)(a.db,"knowledgeBaseDocuments",e));if(t.exists()){const e=t.data()||{};null==n&&(n=e.title||"Env Vault"),null==i&&(i=e.category||""),null==d&&(d=Array.isArray(e.workspaceIds)?e.workspaceIds:[]),null==c&&(c=e.workspace||"Default")}}f=await(0,l.Aj)(e,{title:n||"Env Vault",category:i||"",workspace:c||"Default",workspaceIds:Array.isArray(d)?d:[],userId:t,isEncrypted:!0,encryptionMethod:"user",userEncryptedResult:m.userEncryptedResult,textContent:u,documentKind:s.gV,envConfigMeta:p},{forceVersion:!0}),f&&await(0,l.setCurrentVersion)(e,f)}catch(v){console.error("Env Vault version snapshot failed (non-fatal):",v)}return{ok:!0,envConfigMeta:p,versionId:f}}},698(e,t,n){n.d(t,{J9:()=>m,SA:()=>u,h4:()=>c,mf:()=>p,qR:()=>g,r9:()=>l});var r=n(89379),o=n(5544),a=n(96822),i=n(55472),s=n(67898);function l(){return"undefined"!==typeof crypto&&crypto.randomUUID?"sig-".concat(Date.now(),"-").concat(crypto.randomUUID().slice(0,8)):"sig-".concat(Date.now(),"-").concat(Math.random().toString(36).slice(2,10))}function d(e){if(null===e||"object"!==typeof e)return e;if(Array.isArray(e))return e.map(d).filter(e=>void 0!==e);const t={};for(const r of Object.entries(e)){var n=(0,o.A)(r,2);const e=n[0],a=n[1];void 0!==a&&(t[e]="object"===typeof a&&null!==a?d(a):a)}return t}async function c(e){var t;let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const r=null===(t=(0,s.xI)().currentUser)||void 0===t?void 0:t.uid;
1if(!r)throw new Error("Must be signed in to create an envelope");const o={status:n.status||"draft",userId:r,fieldValues:n.fieldValues||{},signatures:n.signatures||{},createdAt:(0,i.O5)(),completedAt:null};n.documentSnapshot&&(o.documentSnapshot=d(n.documentSnapshot)),n.signerTokens&&(o.signerTokens=d(n.signerTokens)),n.signerBlockIds&&(o.signerBlockIds=d(n.signerBlockIds)),n.signatureMeta&&(o.signatureMeta=d(n.signatureMeta)),n.signingOrder&&Array.isArray(n.signingOrder)&&(o.signingOrder=n.signingOrder),void 0!==n.paymentEnabled&&(o.paymentEnabled=!!n.paymentEnabled),null!=n.paymentAmountCents&&(o.paymentAmountCents=n.paymentAmountCents),null!=n.paymentAmountFieldId&&""!==n.paymentAmountFieldId&&(o.paymentAmountFieldId=n.paymentAmountFieldId),null!=n.paymentProductName&&""!==n.paymentProductName&&(o.paymentProductName=n.paymentProductName),void 0!==n.paymentRevealAfterSignature&&(o.paymentRevealAfterSignature=!!n.paymentRevealAfterSignature),void 0!==n.paymentSubscriptionEnabled&&(o.paymentSubscriptionEnabled=!!n.paymentSubscriptionEnabled),null!=n.paymentSubscriptionAmountCents&&(o.paymentSubscriptionAmountCents=n.paymentSubscriptionAmountCents),null!=n.paymentSubscriptionProductName&&""!==n.paymentSubscriptionProductName&&(o.paymentSubscriptionProductName=n.paymentSubscriptionProductName),null!=n.paymentSubscriptionInterval&&""!==n.paymentSubscriptionInterval&&(o.paymentSubscriptionInterval=n.paymentSubscriptionInterval);const l=await(0,i.gS)((0,i.rJ)(a.db,"knowledgeBaseDocuments",String(e),"envelopes"),o);return{id:l.id,path:l.path}}async function u(e,t,n){const r=(0,i.doc)(a.db,"knowledgeBaseDocuments",String(e),"envelopes",String(t)),o={};void 0!==n.status&&(o.status=n.status),void 0!==n.fieldValues&&(o.fieldValues=n.fieldValues),void 0!==n.signatures&&(o.signatures=n.signatures),void 0!==n.signatureMeta&&(o.signatureMeta=n.signatureMeta),void 0!==n.signerTokens&&(o.signerTokens=n.signerTokens),void 0!==n.signerBlockIds&&(o.signerBlockIds=n.signerBlockIds),void 0!==n.signingOrder&&(o.signingOrder=n.signingOrder),void 0!==n.paymentEnabled&&(o.paymentEnabled=n.paymentEnabled),void 0!==n.paymentAmountCents&&(o.paymentAmountCents=n.paymentAmountCents),void 0!==n.paymentAmountFieldId&&(o.paymentAmountFieldId=n.paymentAmountFieldId),void 0!==n.paymentProductName&&(o.paymentProductName=n.paymentProductName),void 0!==n.paymentRevealAfterSignature&&(o.paymentRevealAfterSignature=n.paymentRevealAfterSignature),void 0!==n.paymentSubscriptionEnabled&&(o.paymentSubscriptionEnabled=n.paymentSubscriptionEnabled),void 0!==n.paymentSubscriptionAmountCents&&(o.paymentSubscriptionAmountCents=n.paymentSubscriptionAmountCents),void 0!==n.paymentSubscriptionProductName&&(o.paymentSubscriptionProductName=n.paymentSubscriptionProductName),void 0!==n.paymentSubscriptionInterval&&(o.paymentSubscriptionInterval=n.paymentSubscriptionInterval),"completed"===n.status&&(o.completedAt=(0,i.O5)()),o.updatedAt=(0,i.O5)(),await(0,i.mZ)(r,o)}async function m(e,t){const n=(0,i.doc)(a.db,"knowledgeBaseDocuments",String(e),"envelopes",String(t)),o=await(0,i.getDoc)(n);return o.exists()?(0,r.A)({id:o.id},o.data()):null}async function p(e){const t=(0,i.rJ)(a.db,"knowledgeBaseDocuments",String(e),"envelopes");return(await(0,i.GG)(t)).docs.map(e=>(0,r.A)({id:e.id},e.data()))}async function g(e){if(!(0,s.xI)().currentUser)throw new Error("Mu
1st be signed in to cancel signature requests");const t=(await p(e)).filter(e=>"pending_signature"===e.status);for(const n of t)await u(e,n.id,{status:"cancelled"});return{cancelled:t.length}}},24489(e,t,n){n.d(t,{DQ:()=>s,Xy:()=>o,cx:()=>l,dO:()=>d});var r=n(52395);const o="based:document-saved",a=new Map,i=new Map;async function s(e){let t=e.organizationId;if(!t)return!1;if(a.has(t))return a.get(t);if(i.has(t))return i.get(t);const n=(async()=>{try{var e;const n=(0,r.getFunctions)(),o=(0,r.httpsCallable)(n,"getVersionControlIntegrationStatus"),i=!0===(null===(e=(await o({organizationId:t})).data)||void 0===e?void 0:e.enabled);return a.set(t,i),i}catch(n){return console.error("resolveVersionControlEnabled:",n),a.set(t,!1),!1}finally{i.delete(t)}})();return i.set(t,n),n}function l(e,t){e&&a.set(e,Boolean(t))}function d(e){if(null==e)return a.clear(),void i.clear();a.delete(e),i.delete(e)}},61962(e,t,n){n.d(t,{p:()=>o});var r=n(81452);function o(e,t){const n=(e||"Untitled").trim()||"Untitled";if(!t||"string"!==typeof t||!t.trim())return{type:"doc",content:[{type:"heading",attrs:{level:1},content:[{type:"text",text:n}]}]};let o=(0,r.r5)(t.trim());if(o.length>0){var a,i;const t=o[0],r=(null===(a=t.content)||void 0===a||null===(i=a.map(e=>e.text).join(""))||void 0===i?void 0:i.trim())||"",s=r.replace(/^#+\s*/,"").trim();(r===e||s===e||"heading"===t.type&&r===n)&&(o=o.slice(1))}return{type:"doc",content:[{type:"heading",attrs:{level:1},content:[{type:"text",text:n}]},...o]}}},78337(e,t,n){n.d(t,{Jm:()=>d,Ks:()=>u,Zg:()=>l,iR:()=>c,u9:()=>s,zc:()=>m});var r=n(89379),o=n(2859),a=n(86836);const i=["documentSignatures","forms","stripe","timer","cursorDevSync","pdfExport","pexels","sopEnhancement","voice","versionControl","documentLock","autoTitle","autoCategory"],s={documentSignatures:"Document signatures",forms:"Forms",stripe:"Stripe",timer:"Timer",cursorDevSync:"Cursor / VS Code extension",pdfExport:"Export as PDF",pexels:"Pexels Images",sopEnhancement:"SOP enhancement",voice:"Voice",versionControl:"Version control",documentLock:"Document lock",autoTitle:"Auto title",autoCategory:"Auto category"},l={documentSignatures:"Add signature areas and send for signing.",forms:"Embed fields to collect responses in the document.",stripe:"Accept payments and invoices with your Stripe account.",timer:"Reference time tracking and billable work.",cursorDevSync:"Reference logging time from Cursor into documents.",pdfExport:"Export the finished document as PDF.",pexels:"Placeholder for royalty-free images where useful.",sopEnhancement:"Structure for procedures and policies.",voice:"Voice-friendly sections or transcript-style notes.",versionControl:"Versioning and change history.",documentLock:"Final / locked document patterns.",autoTitle:"Auto-generated title patterns.",autoCategory:"Auto category patterns."};function d(e,t){var n,r;return!(!e||"object"!==typeof e)&&("stripe"===t?!0===(null===(r=e.stripe)||void 0===r?void 0:r.connected):!0===(null===(n=e[t])||void 0===n?void 0:n.enabled))}function c(e,t){const n=(e||"").toLowerCase(),r=(t||"auto").toLowerCase(),a=[],i=(e,t)=>{const n=a.findIndex(t=>t.id===e);-1===n?a.push({id:e,score:t}):a[n].score=Math.max(a[n].score,t)},s=o.u0.test(e||""),l=o.vz.test(e||"")&&!s&&!o.DF.test(e||""),d=o.ay.has(r);d||s?i("documentSignatures",d?95:80):"letter"===r&&!l&&o.DF.test(e||"")&&i("documentSignatures",70),/\b(forms|a\s+form|the\s+form|form\s+fields?|survey|questionnaire|application|intake|feedback|r\.?s\.?v\.?p|registration)\b/i.test(n)&&i("forms",85),/\b(onboard(?:ing)?|client\s+flow|get\s+client\s+information|collect\s+(answers?|info|information|details)|fill\s+out|fillable)\b/i.test(n)&&(i("forms",88),i("documentSignatures",78));("invoice"===r||/\b(invoice|payment|pay\s|deposit|stripe|ach|wire)\b/i.test(n))&&i("stripe",90),(/\b(hourly|hour\s|time\s+track|billable|retainer|timesheet|timesheet|estimate\s+hours)\b/i.test(n)||"sow"===r)&&i("timer",70),/\b(cursor|ide|vscode|commit\s+log|dev\s+log)\b/i.test(n)&&i("cursorDevSync",55),/\b(pdf|print|download|export)\b/i.test(n)&&i("pdfExport",65),/\b(image|photo|cover|banner|brochure|marketing|flyer|pexels)\b/i.test(n)&&i("pexels",60),("policy"===r||/\b(sop|procedure|policy|playbook|runbook|compliance)\b/i.test(n))&&i("sopEnhancement",75),/\b(voice|transcript|recording|dictat|speak)\b/i.test(n)&&i("voice",55),/\b(version|revision|changelog|track\s+changes)\b/i.test(n)&&i("versionControl",50),/\b(lock|immutable|final|freeze|legal\s+hold)\b/i.test(n)&&i("documentLock",50),/\b(title|untitled|rename)\b/i.test(n)&&i("autoTitle",35),/\b(categor|folder|tag)\b/i.test(n)&&i("autoCategory",35),a.sort((e,t)=>
1t.score-e.score);const c=a.filter(e=>e.score>=50).map(e=>e.id),u=[],m=new Set;for(const o of c)m.has(o)||(m.add(o),u.push(o));return u}function u(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],r=arguments.length>3&&void 0!==arguments[3]?arguments[3]:null,l=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"",c=arguments.length>5&&void 0!==arguments[5]?arguments[5]:"auto";const u={};for(const o of i)u[o]=d(e,o);const m=Array.isArray(t)?t.filter(e=>i.includes(e)):[],p=Array.isArray(n)?n.filter(e=>i.includes(e)):[];for(const o of p)u[o]=!0;const g={};for(const o of i){const e="string"===typeof s[o]?s[o].trim():"";e&&(g[o]=e.slice(0,200))}const h={enabled:u,suggestedIds:m,enabledDuringStep:p,labels:g};!0===r&&(h.signatureBlocksInDraft=!0),!1===r&&(h.signatureBlocksInDraft=!1),!0===u.forms&&(p.includes("forms")||"yes"===(0,a.bS)(l))&&(h.formsInDraft=!0);const f={enabled:u,enabledDuringStep:p,signatureBlocksInDraft:r};return(0,o.uQ)(f,l,c)&&(h.documentSigningPlan=(0,o._t)(l)),h}function m(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.formsEnabled,n=void 0!==t&&t,i=e.documentSignaturesEnabled,l=void 0!==i&&i,d=e.userPrompt,u=void 0===d?"":d,m=e.documentType,p=void 0===m?"auto":m;const g={};for(const r of["forms","documentSignatures"]){const e=s[r];e&&(g[r]=e.slice(0,200))}const h=(0,r.A)({enabled:{forms:!0===n,documentSignatures:!0===l},suggestedIds:c(u,p),enabledDuringStep:[],labels:g},!0===l&&(0,o.uQ)({enabled:{documentSignatures:!0},signatureBlocksInDraft:null},u,p)?{documentSigningPlan:(0,o._t)(u)}:{});return!0===n&&"yes"===(0,a.bS)(u)&&(h.formsInDraft=!0),h}},33945(e,t,n){n.d(t,{ec:()=>C,vF:()=>N,vK:()=>d});var r=n(89379),o=n(88418),a=n(2859);const i=/\b(client|customer|recipient|counterparty|vendor|partner|their)\b/i,s=/\b(me|us|company|provider|sender|author|internal|our)\b/i;function l(e,t){const n=null===e||void 0===e?void 0:e.documentSigningPlan;return"mutual"===n||"client_only"!==n&&(0,a.Tx)(t)}const d=new Set(["proposal","contract","sow","nda","one_pager"]);function c(e){const t=String(e||"").trim();return t?s.test(t)&&!i.test(t)?"me":i.test(t)?"someone_else":null:null}function u(e,t){let n=(arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).presignExpanded,o=void 0!==n&&n;return(0,r.A)((0,r.A)({},e),{},{assigneeType:"me",assigneeEmail:"",signingOrderIndex:t,presignExpanded:!0===o,defaultSignature:"",defaultSignerName:"",defaultSignerEmail:"",defaultSignedAt:""})}function m(e,t,n){const o="string"===typeof t&&t.trim()?t.trim().toLowerCase():"";return(0,r.A)((0,r.A)({},e),{},{assigneeType:"someone_else",assigneeEmail:o,signingOrderIndex:n,presignExpanded:!1,defaultSignature:"",defaultSignerName:"",defaultSignerEmail:"",defaultSignedAt:""})}function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.counterpartyEmail,o=void 0===n?"":n,i=t.userPrompt,s=void 0===i?"":i,d=t.integrationContext,p=void 0===d?null:d;if(!Array.isArray(e))return e;const g=[];if(e.forEach((e,t)=>{"signatureBlock"===e.type&&g.push(t)}),!g.length)return e;const h=l(p,s),f=((0,a.Eh)(s,g.length),e.map(e=>"signatureBlock"!==e.type?e:(0,r.A)((0,r.A)({},e),{},{attrs:(0,r.A)({},e.attrs)})));return g.forEach((e,t)=>((e,t,n)=>{var r;const a=f[e],i=n>1?t+1:1,s=c(null===(r=a.attrs)||void 0===r?void 0:r.label);a.attrs="me"!==s?"someone_else"!==s&&h&&0===t?u(a.attrs,i,{presignExpanded:!0}):m(a.attrs,o,i):u(a.attrs,i,{presignExpanded:!0})})(e,t,g.length)),f}const g=/^(signatures?|signatory|sign\s+here|execution|client\s+signature|authorized\s+signature)$/i,h=/\b(signatory|signer|signed\s+by|signature\s+date|date\s+of\s+signature|job\s+title|printed\s+name|full\s+name)\b/i,f=new Set(["text","textarea","email","date"]);function y(e){return e?"text"===e.type?e.text||"":Array.isArray(e.content)?e.content.map(y).join(""):"":""}function v(e){return!!e&&("signatureBlock"===e.type||!!Array.isArray(e.content)&&e.content.some(v))}function x(e){var t;if(!e||"formBlock"!==e.type)return!1;const n=String((null===(t=e.attrs)||void 0===t?void 0:t.title)||"").trim();if(!n)return!1;if(!(g.test(n)||/\bsignature\b/i.test(n)))return!1;const r=function(e){var t;if(null===e||void 0===e||null===(t=e.attrs)||void 0===t||!t.fields)return[];try{const t="string"===typeof e.attrs.fields?JSON.parse(e.attrs.fields):e.attrs.fields;return Array.isArray(t)?t:[]}catch(n){return[]}}(e);if(!r.length)return!1;if(!r.every(e=>f.has(e.type)))return!1;const o=r.map(e=>String(e.label||"").toLowerCase()),a=o.some(e=>h.test(e)),i=o.some(e=>/\b(name|signatory|signer)\b/.test(e))&&o.some(e=>/\bdate\b/.test(e));return a||i}function b(e){if("paragraph"!==e.type)return!1;const t=y(e).replace(/\u00a0/g," ").trim();return!!t&&(!!/^signature\s*:?\s*(?:[_\s\u2011\u2013-]|\u2026|\.{3,})+$/i.test(t)||(!!/^date\s*:?\s*(?:[_\s\u2011\u2013-]|\u2026|\.{3,})+$/i.test(t)||(!!/^[_\s\u2011\u2013-]{8,}$/.test(t)||!!(/signature\s*:?\s*[_\s-]+/i.test(t)&&/date\s*:?\s*[_\s-]+/i.test(t)&&t.length<320))))}function w(e){return e&&("paragraph"===e.type||"heading"===e.type)?y(e).replace(/\u00a0/g," ").trim():""}function k(e){if(!e||"paragraph"!==e.type&&"heading"!==e.type)return!1;const t=w(e);return!!t&&(!!/^signature\s*:?\s*$/i.test(t)||(!!/^signature\s*:?\s*(?:[_\s\u2026.\u2011\u2013-]+)$/i.test(t)||b(e)))}function A(e){if(!e||"paragraph"!==e.type&&"heading"!==e.type)return!1;const t=w(e);return!t||(!!b(e)||(!!/^date\s*:?\s*(?:[_\s\u2026.\u2011\u2013-]+)?$/i.test(t)||t.length<=80&&!/[.!?]/.test(t)&&!/^\d+\.\s/.test(t)))}function j(){let e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).label,t=void 0===e?"":e;return{type:"signatureBlock",attrs:{blockId:(0,o.G)(),label:String(t||"").slice(0,240),assigneeEmail:"",assigneeType:"me",signingOrderIndex:null,signatureAlign:"full",defaultSignature:"",defaultSignerName:"",defaultSignerEmail:"",defaultSignedAt:"",presignExpanded:!1}}}function N(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!e||"doc"!==e.type||!Array.isArray(e.content))return e;const n=t.documentType,o=void 0===n?"auto":n,i=t.integrationContext,s=void 0===i?null:i,d=t.counterpartyEmail,u=void 0===d?"":d,m=t.defaultAssigneeEmail,g=void 0===m?"":m,h=t.userPrompt,f=void 0===h?"":h,y="string"===typeof u&&u.trim()?u.trim().toLowerCase():"string"===typeof g&&g.trim()?g.trim().toLowerCase():"";if(!(0,a.uQ)(s,f,o))return e;let N=function(e){if(!Array.isArray(e))return e;const t=[];for(const r of e){if(x(r)){var n;const e=String((null===(n=r.attrs)||void 0===n?void 0:n.title)||"").trim(),o=/^signature$/i.test(e)?"":e;t.push(j({label:o}));continue}t.push(r)}return t}(e.content);N=function(e){if(!Array.isArray(e))return e;const t=[];let n=0;for(;n<e.length;){const r=e[n];if(k(r)){let o=n+1;for(;o<e.length&&A(e[o]);)o+=1;if(o>n+1||b(r)||/^signature\s*:?\s*(?:[_\s\u2026.\u2011\u2013-]+)/i.test(w(r))){t.push(j()),n=o;continue}}t.push(r),n+=1}return t}(N),N=function(e){if(!Array.isArray(e))return e;const t=[...e];for(;t.length>0;){const e=t[t.length-1];if("paragraph"!==e.type||!b(e))break;t.pop()}return t}(N),v({type:"doc",content:N})||(N=[...N,j()]);const C=l(s,f),S=N.filter(e=>"signatureBlock"===e.type).length;return C&&1===S&&(N=[...N,j({label:"Client"})]),N=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.userPrompt,r=void 0===n?"":n,o=t.integrationContext,i=void 0===o?null:o;if(!Array.isArray(e))return e;const s=[];if(e.forEach((e,t)=>{"signatureBlock"===e.type&&s.push(t)}),s.length<=1)return e;const d=l(i,r),u=(0,a.Eh)(r,s.length);if(d){if(2===s.length||u)return e;const t=new Set([s[0]]),n=s.find((t,n)=>{var r;return n>0&&"someone_else"===c(null===(r=e[t].attrs)||void 0===r?void 0:r.label)});
1return t.add(null!=n?n:s[1]),e.filter((e,n)=>"signatureBlock"!==e.type||t.has(n))}if(u)return e;let m=s[s.length-1];for(let a=s.length-1;a>=0;a-=1){var p;const t=s[a];if("someone_else"===c(null===(p=e[t].attrs)||void 0===p?void 0:p.label)){m=t;break}}return e.filter((e,t)=>"signatureBlock"!==e.type||t===m)}(N,{userPrompt:f,integrationContext:s}),N=p(N,{counterpartyEmail:y,userPrompt:f,integrationContext:s}),(0,r.A)((0,r.A)({},e),{},{content:N})}function C(e){return N(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}},95523(e,t,n){n.d(t,{Gp:()=>s,LD:()=>l,Nn:()=>i,ZE:()=>r.ZE,rg:()=>a});var r=n(84441);const o="unlock document";function a(e){return!(null===e||void 0===e||!e.locked)||(0,r.z7)(e)}function i(e){const t=!1!==(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).isGlobalView;return e?e.locked?{showInput:!0,kind:"locked",requiredPhrase:o,label:'Type "unlock document"',placeholder:o}:(0,r.z7)(e)&&t?{showInput:!0,kind:"envVault",requiredPhrase:r.ZE,label:'Type "'.concat(r.ZE,'"'),placeholder:r.ZE}:{showInput:!1,kind:null}:{showInput:!1,kind:null}}function s(e,t){return i(e,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{}).showInput?{unlockPhrase:t}:{}}function l(e){const t=String(e||"").toLowerCase();return t.includes("unlock phrase")||t.includes("incorrect unlock")||t.includes("delete secrets")||t.includes("secrets document")}},709(e,t,n){n.d(t,{EG:()=>x,F2:()=>y,K:()=>v,P3:()=>i,Wb:()=>h,Zj:()=>p,iy:()=>f,j4:()=>a,x:()=>m});var r=n(5544),o=n(89379);const a=["development","preview","production"],i=["plaintext","sensitive","secret"],s={development:"development",staging:"preview",production:"production"},l={plaintext:"PUBLIC",sensitive:"SENSITIVE",secret:"SECRET"};function d(e){const t=String(e||"").trim().toLowerCase();return a.includes(t)?t:null}function c(e){const t=String(e||"").trim().toLowerCase();return"public"===t||"plain"===t||"plain text"===t||"plain_text"===t?"plaintext":i.includes(t)?t:"sensitive"}function u(e){if(null==e)return null;const t=Array.isArray(e)?e:String(e).split(/[\s,]+/).filter(Boolean),n=[],r=new Set;for(const o of t){const e=String(o||"").trim();e&&!r.has(e)&&(r.add(e),n.push(e))}return n.length>0?n:null}function m(e){const t=e&&"object"===typeof e?e:{},n=(0,o.A)({},s),a=t.configToEnvironment&&"object"===typeof t.configToEnvironment?t.configToEnvironment:{};for(const o of Object.entries(a)){var i=(0,r.A)(o,2);const e=i[0],t=i[1],a=String(e||"").trim(),s=d(t);a&&s&&(n[a]=s)}return{projectId:String(t.projectId||"").trim(),projectName:String(t.projectName||"").trim(),configToEnvironment:n,keyAllowlist:u(t.keyAllowlist),visibility:c(t.visibility)}}function p(e,t,n){const r=m(e),o=String(t||"").trim(),a=String(n||"").trim();return o&&a&&o!==a?(r.configToEnvironment[o]&&(r.configToEnvironment[a]=r.configToEnvironment[o],o in s||delete r.configToEnvironment[o]),r):r}function g(e){const t=[];if(!e||"object"!==typeof e)return t;for(const o of Object.entries(e)){var n=(0,r.A)(o,2);const e=n[0],a=n[1],i=String(e||"").trim();i&&t.push({name:i,value:null==a?"":String(a)})}return t.sort((e,t)=>e.name.localeCompare(t.name))}function h(e){const t=String((null===e||void 0===e?void 0:e.configName)||"").trim(),n=m(null===e||void 0===e?void 0:e.settings),r=function(e,t,n){var r;const o=d(n);if(o)return o;const a=String(e||"").trim(),i=null===t||void 0===t||null===(r=t.configToEnvironment)||void 0===r?void 0:r[a];return i||d(a)}(t,n,null===e||void 0===e?void 0:e.environmentOverride),o=null==(null===e||void 0===e?void 0:e.selectedNames)?null:new Set(u(e.selectedNames)||[]),a=n.keyAllowlist?new Set(n.keyAllowlist):null,i=[],s=[];let l=0,c=0;for(const d of g(null===e||void 0===e?void 0:e.secrets))""!==d.value?(!a||a.has(d.name))&&(!o||o.has(d.name))?(i.push(d.name),s.push(d)):c+=1:l+=1;let p=null;return n.projectId?r?0===i.length&&(p="No keys to push"):p="Choose an EAS environment for this config":p="Set an Expo project id on this vault",{ok:!p,error:p,sourceConfig:t,environment:r,projectId:n.projectId,projectName:n.projectName,visibility:n.visibility,namesToPush:i,skippedEmpty:l,skippedFiltered:c,toUpsert:s}}function f(e){const t=Array.isArray(null===e||void 0===e?void 0:e.namesToPush)?e.namesToPush.length:0,n=(null===e||void 0===e?void 0:e.environment)||"environment",r=String((null===e||void 0===e?void 0:e.projectName)||(null===e||void 0===e?void 0:e.projectId)||"this Expo project").trim();return"Push ".concat(t," key").concat(1===t?"":"s"," to EAS ").concat(n," on ").concat(r)}function y(e){const t=String((null===e||void 0===e?void 0:e.sourceConfig)||"").trim(),n=String((null===e||void 0===e?void 0:e.destConfig)||"").trim(),r
1=Array.isArray(null===e||void 0===e?void 0:e.configNames)?e.configNames.map(e=>String(e).trim()):[],o=null==(null===e||void 0===e?void 0:e.selectedNames)?null:new Set(u(e.selectedNames)||[]),a=[],i=[];let s=0,l=0;for(const c of g(null===e||void 0===e?void 0:e.sourceSecrets))""!==c.value?!o||o.has(c.name)?(a.push(c.name),i.push(c)):l+=1:s+=1;let d=null;return t?n?t===n?d="Pick a different destination config":r.length>0&&!r.includes(n)?d="Destination config not found":0===a.length&&(d="No keys to copy"):d="Pick a destination config":d="Pick a source config",{ok:!d,error:d,sourceConfig:t,destConfig:n,namesToPush:a,skippedEmpty:s,skippedFiltered:l,toUpsert:i}}function v(e){const t=Array.isArray(null===e||void 0===e?void 0:e.namesToPush)?e.namesToPush.length:0,n=String((null===e||void 0===e?void 0:e.sourceConfig)||"this config").trim(),r=String((null===e||void 0===e?void 0:e.destConfig)||"destination").trim();return"Copy ".concat(t," key").concat(1===t?"":"s"," from ").concat(n," to ").concat(r)}function x(e){return l[c(e)]||"SENSITIVE"}},55305(e,t,n){function r(e){var t,n,r,o;const a=null===e||void 0===e||null===(t=e.content)||void 0===t?void 0:t[0],i=null===a||void 0===a||null===(n=a.content)||void 0===n||null===(r=n[0])||void 0===r||null===(o=r.text)||void 0===o?void 0:o.trim();return i&&i.length?i:"Untitled"}function o(e){return null!==e&&void 0!==e&&e.content?e.content.map(e=>e.content?e.content.map(e=>e.text||"").join(""):"").join("\n").replace(/\n{3,}/g,"\n\n").trim():""}n.d(t,{Br:()=>o,mJ:()=>r})},84441(e,t,n){n.d(t,{$W:()=>g,FS:()=>m,LI:()=>c,QN:()=>s,ZE:()=>l,b_:()=>d,gV:()=>i,io:()=>f,rX:()=>u,sh:()=>v,uY:()=>y,z7:()=>h});var r=n(89379),o=n(5544),a=n(709);const i="envVault",s="development",l="delete secrets",d="https://images.pexels.com/photos/5474298/pexels-photo-5474298.jpeg?auto=compress&cs=tinysrgb&dpr=2&w=1200";function c(){return{version:1,configs:{[s]:{},staging:{},production:{}},easSync:(0,a.x)(null)}}function u(e){const t=c();if(!e||"object"!==typeof e)return t;const n=e.configs&&"object"===typeof e.configs?e.configs:{},r={};for(const a of Object.entries(n)){var i=(0,o.A)(a,2);const e=i[0],t=i[1],n=String(e||"").trim();if(n&&(r[n]={},t&&"object"===typeof t&&!Array.isArray(t)))for(const a of Object.entries(t)){var s=(0,o.A)(a,2);const e=s[0],t=s[1],i=String(e||"").trim();i&&(r[n][i]=null==t?"":String(t))}}return 0===Object.keys(r).length?t:{version:"number"===typeof e.version?e.version:1,configs:r,easSync:(0,a.x)(e.easSync)}}function m(e){const t=Object.entries(e||{}).sort((e,t)=>{let n=(0,o.A)(e,1)[0],r=(0,o.A)(t,1)[0];return n.localeCompare(r)});return 0===t.length?"# KEY: value or KEY=value\n":"".concat(t.map(e=>{let t=(0,o.A)(e,2),n=t[0],r=t[1];const a=String(n),i=String(null!==r&&void 0!==r?r:"");return""===i||/[\n\r#:]/.test(i)||/^\s|\s$/.test(i)?"".concat(a,": ").concat(JSON.stringify(i)):"".concat(a,": ").concat(i)}).join("\n"),"\n")}function p(e){const t=e.indexOf("="),n=e.indexOf(":");let r=-1;if(t>0&&n>0)r=Math.min(t,n);else if(t>0)r=t;else{if(!(n>0))return null;r=n}const o=e.slice(0,r).trim();return!o||/\s/.test(o)?null:{key:o,rawVal:e.slice(r+1).trim()}}function g(e){const t={},n=String(e||"").split(/\r?\n/);for(const o of n){let e=o.trim();if(!e||e.startsWith("#"))continue;if(/^export\s+/i.test(e)&&(e=e.replace(/^export\s+/i,"").trim(),!e||e.startsWith("#")))continue;const n=p(e);if(!n)continue;let a=n.rawVal;if(a.startsWith('"')&&a.endsWith('"')||a.startsWith("'")&&a.endsWith("'"))try{a=JSON.parse(a.startsWith("'")?'"'.concat(a.slice(1,-1).replace(/"/g,'\\"'),'"'):a)}catch(r){a=a.slice(1,-1)}t[n.key]=String(a)}return t}function h(e){return!!e&&e.documentKind===i}function f(e,t,n){const i=u(e),s=String(t||"").trim(),l=String(n||"").trim();if(!s)return{ok:!1,error:"Config not found"};if(!l)return{ok:!1,error:"Enter a config name"};if(!i.configs[s])return{ok:!1,error:"Config not found"};if(s===l)return{ok:!0,payload:i,unchanged:!0};if(i.configs[l])return{ok:!1,error:"Config already exists"};const d={};for(const r of Object.entries(i.configs)){var c=(0,o.A)(r,2);const e=c[0],t=c[1];d[e===s?l:e]=t}const m=(0,a.Zj)(i.easSync,s,l);return{ok:!0,payload:(0,r.A)((0,r.A)({},i),{},{configs:d,easSync:m})}}function y(e,t,n){const o=String(t||"").trim(),a=u(e);if(!o||!a.configs[o])throw new Error("Destination config not found");const i=(0,r.A)({},a.configs[o]);for(const r of Array.isArray(n)?n:[]){const e=String((null===r||void 0===r?void 0:r.name)||"").trim();e&&(i[e]=null==r.value?"":String(r.value))}return(0,r.A)((0,r.A)({},a),{},{configs:(0,r.A)((0,r.A)({},a.configs),{},{[o]:i})})}function v(e){const t=null!==e&&void 0!==e&&e.configs&&"object"===typeof e.configs?e.configs:{},n={};for(const a of Object.entries(t)){var r=(0,o.A)(a,2);const e=r[0],t=r[1];n[e]={secretCount:t&&"object"===typeof t?Object.keys(t).length:0}}return n}},60678(e,t,n){n.d(t,{AD:()=>i,B0:()=>o,W0:()=>r,x$:()=>s});const r=e=>{if(!e)return null;try{if("function"===typeof e.toDate){const t=e.toDate();return isNaN(t.getTime())?null:t}if("object"===typeof e&&"number"===typeof e._seconds){const t=1e3*e._seconds+Math.floor((e._nanoseconds||0)/1e6),n=new Date(t);return isNaN(n.getTime())?null:n}if(e instanceof Date)return isNaN(e.getTime())?null:e;if("string"===typeof e){const t=new Date(e);return isNaN(t.getTime())?null:t}if("number"===typeof e){const t=e<1e10?new Date(1e3*e):new Date(e);return isNaN(t.getTime())?null:t}const t=new Date(e);return isNaN(t.getTime())?null:t}catch(t){return null}},o=e=>e&&(r(e.updatedAt)||r(e.createdAt)||r(e.uploadedAt))||null,a=e=>
1!e||isNaN(e.getTime())?"":e.toLocaleString("en-US",{dateStyle:"medium",timeStyle:"short"}),i=e=>{if(!e)return{visibleText:"",title:""};const t=r(e.createdAt),n=r(e.uploadedAt),o=r(e.updatedAt),i=t||n,l=(e,t)=>{const n=a(e),r=a(t);return e&&t&&Math.abs(t.getTime()-e.getTime())<=9e4?n?"Created and last edited ".concat(n):"":e&&t?"Created: ".concat(n," \xb7 Last edited: ").concat(r):t?"Last edited: ".concat(r):e?"Created: ".concat(n):""};if(!i&&!o)return{visibleText:"",title:""};if(!o){return{visibleText:i?"Created ".concat(s(e.createdAt||e.uploadedAt)):"",title:i?n&&!t?"Uploaded: ".concat(a(n)):"Created: ".concat(a(i)):""}}if(!i)return{visibleText:"Edited ".concat(s(e.updatedAt)),title:"Last edited: ".concat(a(o))};return Math.abs(o.getTime()-i.getTime())<=9e4?{visibleText:"Created ".concat(s(e.createdAt||e.uploadedAt)),title:l(i,o)}:{visibleText:"Edited ".concat(s(e.updatedAt)),title:l(i,o)}},s=e=>{const t=r(e);if(!t)return"";try{const e=new Date;if(t.toDateString()===e.toDateString()){const n=e-t,r=Math.floor(n/1e3),o=Math.floor(r/60),a=Math.floor(o/60);return o<1?"just now":o<60?"".concat(o," ").concat(1===o?"minute":"minutes"," ago"):"".concat(a," ").concat(1===a?"hour":"hours"," ago")}const n=new Date(e);n.setDate(e.getDate()-1);if(t.toDateString()===n.toDateString())return"Yesterday";const r=new Date(e);if(r.setDate(e.getDate()-7),r.setHours(0,0,0,0),t>=r){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][t.getDay()]}const o=t.toLocaleDateString("en-US",{month:"short"}),a=t.getDate(),i=t.getFullYear();return"".concat(o," ").concat(a,", ").concat(i)}catch(n){return console.error("Error formatting date:",n),""}}},39599(e,t,n){n.d(t,{AQ:()=>o,GY:()=>p,Hr:()=>c,II:()=>d,hQ:()=>u,tg:()=>m});var r=n(17070);const o=[{id:"client-services",label:"Client services / consulting"},{id:"agency-creative",label:"Agency / creative"},{id:"ops-internal",label:"Ops / internal docs & SOPs"},{id:"dev-technical",label:"Dev / technical"},{id:"personal-other",label:"Personal / other"}],a={"client-services":["timer","pdfExport","versionControl"],"agency-creative":["pexels","pdfExport","forms","autoTitle","autoCategory"],"ops-internal":["sopEnhancement","versionControl","autoTitle","autoCategory"],"dev-technical":["versionControl","cursorDevSync","timer","voice","envVault"],"personal-other":["autoTitle","autoCategory"]},i={"client-services":["Clients","Proposals","Contracts","Billing","Meetings","Legal"],"agency-creative":["Clients","Campaigns","Creative","Brand","Marketing","Deliverables"],"ops-internal":["SOPs","Policies","Operations","HR","Compliance","Training"],"dev-technical":["Engineering","Product","Specs","Runbooks","IT","Incidents"],"personal-other":[...r.MT]},s={signatures:["Legal","Contracts"],billing:["Billing"],forms:["Intake"],sop:["SOPs","Policies"],pdf:["Deliverables"],visuals:["Brand","Creative"],cursor:["Engineering"],lock:["Policies"]},l=[{id:"signatures",text:"Do you send agreements or proposals for signature?",integrationIds:["documentSignatures","pdfExport"],showFor:["client-services","agency-creative","ops-internal","personal-other"]},{id:"billing",text:"Do you bill clients or track billable hours?",integrationIds:["timer"],showFor:["client-services","agency-creative","personal-other"]},{id:"cursor",text:"Do you use Cursor for coding?",integrationIds:["cursorDevSync","envVault"],showFor:["dev-technical"]},{id:"envVault",text:"Want to store project env vars encrypted in Based?",integrationIds:["envVault"],showFor:["dev-technical","ops-internal","personal-other"]},{id:"pdf",text:"Need polished PDFs for clients or compliance?",integrationIds:["pdfExport"],showFor:["ops-internal","dev-technical","personal-other"]},{id:"forms",text:"Collect applications, RSVPs, or intake in documents?",integrationIds:["forms"],showFor:["client-services","ops-internal","dev-technical","personal-other"]},{id:"visuals",text:"Heavy on visuals \u2014 decks, posts, or docs with images?",integrationIds:["pexels"],showFor:["client-services","ops-internal","dev-technical","personal-other"]},{id:"voice",text:"Prefer speaking notes over typing sometimes?",integrationIds:["voice"],show
1For:["client-services","agency-creative","ops-internal","personal-other"]},{id:"sop",text:"Iterate on policies or SOPs with AI structure?",integrationIds:["sopEnhancement"],showFor:["client-services","agency-creative","dev-technical","personal-other"]},{id:"lock",text:"Need to lock finalized documents to prevent changes?",integrationIds:["documentLock"],showFor:["ops-internal","client-services"]}];function d(e){return l.filter(t=>!t.showFor||t.showFor.includes(e))}const c={documentSignatures:"Document signatures",forms:"Forms",timer:"Timer",cursorDevSync:"Cursor / VS Code extension",envVault:"Env Vault",pdfExport:"Export as PDF",pexels:"Pexels Images",sopEnhancement:"AI Enhancement (SOP)",voice:"Voice",versionControl:"Version control",documentLock:"Document lock",autoTitle:"Auto title",autoCategory:"Auto category"},u={documentSignatures:"Add signature fields and send documents for signing.",forms:"Embed form fields to collect responses inside documents.",timer:"Track time on documents \u2014 great for billing and invoicing.",cursorDevSync:"Install Based in Cursor: time tracking plus optional Env Vault secrets sync.",envVault:"Store encrypted environment variables and sync them in Cursor / VS Code.",pdfExport:"Download any document as a formatted PDF.",pexels:"Search and insert royalty-free images from Pexels.",sopEnhancement:"Use AI to structure and enhance procedures and policies.",voice:"Add text via voice input from the document toolbar.",versionControl:"Save document history and restore previous versions.",documentLock:"Lock documents to prevent accidental deletion.",autoTitle:"Automatically suggest titles for new documents.",autoCategory:"Automatically assign categories based on content."};function m(e,t){const n=new Set(a[e]||[]);n.add("sopEnhancement");for(const r of d(e))if(t[r.id])for(const e of r.integrationIds)n.add(e);return{integrationIds:[...n],showStripeCta:!!t.stripe,showWebsiteChatbotCta:!!t.chatbot}}function p(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=i[e];if(!n)return[...r.MT];const o=[...n];for(const r of d(e)){if(!t[r.id])continue;const e=s[r.id];if(e)for(const t of e)o.push(t)}return(0,r.cP)(o)}},60492(e,t,n){n.d(t,{O3:()=>a,Xe:()=>o});var r=n(42773);function o(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.linkId,n=e.mascotMode,o=void 0!==n&&n,a=e.origin,i=e.customDomain,s=e.mascotDomain;if(!t)return"";if(o){const e=a&&!String(a).includes("docs.")?a:function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;return(0,r.tu)(e)}(s);return"".concat(e,"/mascot/").concat(t)}const l=a||(0,r.XI)(i);return"".concat(l,"/shared/").concat(t)}async function a(e){let t=e.workspaceId,n=e.documentId,r=e.phrase,a=e.idToken,i=e.mascotDomain,s=void 0===i?null:i;const l=(r||"").replace(/\s+/g," ").trim();if(!l)throw new Error("Select text before creating a mascot link.");if(l.length>500)throw new Error("Phrase is too long (max ".concat(500," characters)."));if(!t||!n||!a)throw new Error("Missing workspace, document, or auth.");const d=await fetch("".concat("https://us-central1-aiknowledgebase-7427e.cloudfunctions.net/createShareableLink","?knowledgeBaseId=").concat(encodeURIComponent(t)),{method:"POST",headers:{Authorization:"Bearer ".concat(a),"Content-Type":"application/json"},body:JSON.stringify({isPublic:!0,documentId:n,mascotMode:!0,mascotPhrase:l,mascotPhraseOnly:!0,enabledViews:"traditional",commentsEnabled:!1,agentConfig:{enabled:!1},emailOnOpen:!0})});if(!d.ok){let e="Could not create mascot link.";try{const t=await d.json();null!==t&&void 0!==t&&t.error&&(e=t.error)}catch(u){}throw new Error(e)}const c=(await d.json()).linkId;if(!c)throw new Error("Share link was created without an id.");return{linkId:c,url:o({linkId:c,mascotMode:!0,mascotDomain:s})}}},98688(e,t,n){n.d(t,{MF:()=>s,MH:()=>c,OB:()=>d,n5:()=>l,zn:()=>p});var r=n(28044);const o="[Encrypted Content]",a=7e3;function i(e){return"string"===typeof e?e:""}function s(e){return i(e).replace(/\r\n/g,"\n").replace(/[ \t\f\v]+/g," ").replace(/ *\n */g,"\n").replace(/\n{3,}/g,"\n\n").trim()}function l(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";const n=s(e),r=s(t);if(!n||!r)return n;const o=n.split("\n");return(o[0]||"").trim().toLowerCase()===r.toLowerCase()?s(o.slice(1).join("\n")):n}function d(e){let t=e;if("string"===typeof t)try{t=JSON.parse(t)}catch(a){return s(t)}if(!t||"object"!==typeof t)return"";const n=[],r=e=>{e&&"object"===typeof e&&("text"!==e.type||"string"!==typeof e.text?"hardBreak"!==e.type?Array.isArray(e.content)&&e.content.forEach(r):n.push("\n"):n.push(e.text))},o=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;if(e&&"object"===typeof e){if("bulletList"===e.type)return(e.content||[]).forEac
1h(e=>o(e,{kind:"bullet"})),void n.push("\n");if("orderedList"===e.type){var a;let t=Number(null===(a=e.attrs)||void 0===a?void 0:a.start)>0?Number(e.attrs.start):1;return(e.content||[]).forEach(e=>{o(e,{kind:"ordered",index:t}),t+=1}),void n.push("\n")}if("taskList"===e.type)return(e.content||[]).forEach(e=>o(e,{kind:"task"})),void n.push("\n");if("listItem"===e.type||"taskItem"===e.type){let a="\u2022 ";if("ordered"===(null===t||void 0===t?void 0:t.kind))a="".concat(t.index,". ");else if("task"===(null===t||void 0===t?void 0:t.kind)){var i;a=null!==(i=e.attrs)&&void 0!==i&&i.checked?"[x] ":"[ ] "}n.push(a);return(Array.isArray(e.content)?e.content:[]).forEach((e,a)=>{a>0&&("paragraph"===e.type||"bulletList"===e.type||"orderedList"===e.type)&&n.push("\n"),"bulletList"===e.type||"orderedList"===e.type||"taskList"===e.type?o(e,null):"paragraph"===e.type||"heading"===e.type?r(e):o(e,t)}),void n.push("\n")}"text"!==e.type&&"hardBreak"!==e.type?(Array.isArray(e.content)&&e.content.forEach(e=>o(e,t)),"paragraph"!==e.type&&"heading"!==e.type&&"blockquote"!==e.type&&"tableRow"!==e.type||n.push("\n")):r(e)}};return o(t,null),s(n.join(""))}function c(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};const r=i(n.title||(null===e||void 0===e?void 0:e.title)||(null===e||void 0===e?void 0:e.fileName)),a=!0===n.preferLiveText,c=d(null===e||void 0===e?void 0:e.editorJson);if(c)return l(c,r);const u=s(t);if(a&&u&&u!==o)return l(u,r);if(!e||"object"!==typeof e)return l(u,r);const m=s(e.textContent);if(m&&m!==o)return l(m,r);const p=s(i(e.editorHtml||e.formattedContent).replace(/<br\s*\/?>/gi,"\n").replace(/<\/(p|div|h[1-6]|tr|blockquote)>/gi,"\n").replace(/<li[^>]*>/gi,"\n\u2022 ").replace(/<\/li>/gi,"\n").replace(/<[^>]+>/g," ").replace(/&nbsp;/gi," ").replace(/&amp;/gi,"&").replace(/&lt;/gi,"<").replace(/&gt;/gi,">").replace(/&quot;/gi,'"').replace(/&#39;/gi,"'"));return p?l(p,r):u&&u!==o?l(u,r):""}function u(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.to,n=void 0===t?"":t,r=e.subject,o=void 0===r?"":r,a=e.body,s=void 0===a?"":a;const l=i(n).trim(),d=[],c=i(o).trim(),u=i(s);return c&&d.push("subject=".concat(encodeURIComponent(c))),u&&d.push("body=".concat(encodeURIComponent(u))),"mailto:".concat(l).concat(d.length?"?".concat(d.join("&")):"")}function m(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.to,n=void 0===t?"":t,r=e.subject,o=e.body,l=e.maxLength,d=void 0===l?a:l,c=i(o),m=u({to:n,subject:r,body:c});if(m.length<=d)return{href:m,body:c,truncated:!1};let p=0,g=c.length,h="";for(;p<=g;){const e=Math.floor((p+g)/2),t=s(c.slice(0,e))+"\n\n[\u2026]";u({to:n,subject:r,body:t}).length<=d?(h=t,p=e+1):g=e-1}if(!h){const e=u({to:n,subject:r});return e.length<=d?{href:e,body:"",truncated:!0}:{href:u({to:n,subject:"Document"}),body:"",truncated:!0}}return{href:u({to:n,subject:r,body:h}),body:h,truncated:!0}}async function p(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};const t=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.title,n=void 0===t?"":t,o=e.body,d=void 0===o?"":o,c=e.to,p=void 0===c?"":c,g=e.maxLength,h=void 0===g?a:g;const f=i(n).trim()||"Document",y=l(s(d),f),v=i(p).trim()||(0,r.YS)(y)||"";if(!y)return{to:v,subject:f,body:"",fullBody:"",href:u({to:v,subject:f}),truncated:!1,empty:!0,clipboardFallback:!1};const x=m({to:v,subject:f,body:y,maxLength:h});return{to:v,subject:f,body:x.body,fullBody:y,href:x.href,truncated:x.truncated,empty:!1,clipboardFallback:x.truncated}}(e);if(t.empty&&!t.to)return{opened:!1,truncated:!1,empty:!0,href:t.href,copiedToClipboard:!1,reason:"empty"};if("undefined"===typeof window||!window.location)return{opened:!1,truncated:t.truncated,empty:t.empty,href:t.href,copiedToClipboard:!1,reason:"no-window"};let n=t.href,o=!1,d=t.truncated;if(t.clipboardFallback&&t.fullBody)try{var c,p;if(null!==(c=navigator)&&void 0!==c&&null!==(p=c.clipboard)&&void 0!==p&&p.writeText){await navigator.clipboard.writeText(t.fullBody),o=!0;const r="The full letter is on your clipboard \u2014 press Cmd+V (or Ctrl+V) to paste it here.";n=m({to:t.to,subject:t.subject,body:r,maxLength:e.maxLength||a}).href,d=!0}}catch(g){}return window.location.href=n,{opened:!0,truncated:d,empty:t.empty,href:n,copiedToClipboard:o}}},31238(e,t,n){n.d(t,{S:()=>a});var r=n(12589),o=n(81452);function a(e){const t=((arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).defaultProductName||"").trim();let n=e;if("string"===typeof n)try{n=JSON.parse(n)}catch(d){return{editorJson:e,paymentEnabled:!1,paymentLinks:[],changed:!1}}if(!n||"object"!==typeof n)return{editorJson:e,paymentEnabled:!1,paymentLinks:[],changed:!1};const a=[];let i=!1,s=0;const l=e=>{if(e&&"object"===typeof e){if("paymentButton"===e.type){s+=1,e.attrs=e.attrs||{},e.attrs.paymentLinkId||(e.attrs.paymentLinkId=(0,r.d)(),i=!0);const n=function(e){const t=(null===e||void 0===e?void 0:e.attrs)||{};if(null!=t.amountCents){const e=Number(t.amountCents);if(Number.isFinite(e)&&e>0)return Math.round(e)}if(t.label){const e=(0,o.mh)(String(t.label).replace(/^pay\s*/i,"").trim());if(e)return e}return null}(e);
1null!=n&&e.attrs.amountCents!==n&&(e.attrs.amountCents=n,i=!0);const l=e.attrs.productName?String(e.attrs.productName).slice(0,200):t?"".concat(t).concat(s>1?" (".concat(s,")"):"").slice(0,200):null;a.push({id:e.attrs.paymentLinkId,amountCents:n,productName:l})}Array.isArray(e.content)&&e.content.forEach(l)}};return Array.isArray(n.content)?n.content.forEach(l):l(n),{editorJson:i?n:e,paymentEnabled:a.length>0,paymentLinks:a,changed:i}}},18053(e,t,n){n.d(t,{j1:()=>i});const r=new Set(["image/gif","image/svg+xml"]),o={"image/webp":"webp","image/jpeg":"jpg","image/png":"png","image/gif":"gif","image/svg+xml":"svg"};function a(e){if(o[e])return o[e];const t=(String(arguments.length>1&&void 0!==arguments[1]?arguments[1]:"").split(".").pop()||"").replace(/[^a-zA-Z0-9]/g,"");return t.length?t.toLowerCase():"png"}async function i(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};const n=t.maxDimension||1600,o=t.quality||.82,i=(null===e||void 0===e?void 0:e.type)||"image/png",s=(t,n)=>({blob:t,contentType:n,extension:a(n,null===e||void 0===e?void 0:e.name),metadata:{contentType:n,cacheControl:"public, max-age=31536000, immutable"}});if(!e||r.has(i)||"undefined"===typeof document)return s(e,i);try{const t=await function(e){return"function"===typeof createImageBitmap?createImageBitmap(e):new Promise((t,n)=>{const r=URL.createObjectURL(e),o=new Image;o.onload=()=>{URL.revokeObjectURL(r),t(o)},o.onerror=()=>{URL.revokeObjectURL(r),n(new Error("decode failed"))},o.src=r})}(e),r=t.width||t.naturalWidth||0,a=t.height||t.naturalHeight||0;if(!r||!a)return s(e,i);const l=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1600;const r=Math.max(Number(e)||0,Number(t)||0);return!r||!n||r<=n?1:n/r}(r,a,n),d=document.createElement("canvas");d.width=Math.max(1,Math.round(r*l)),d.height=Math.max(1,Math.round(a*l));const c=d.getContext("2d");if(!c)return s(e,i);c.drawImage(t,0,0,d.width,d.height),"function"===typeof t.close&&t.close();const u=function(){if("undefined"===typeof document)return!1;try{const e=document.createElement("canvas");return e.width=1,e.height=1,e.toDataURL("image/webp").startsWith("data:image/webp")}catch(e){return!1}}()?"image/webp":"image/jpeg",m=await function(e,t,n){return new Promise(r=>{"function"===typeof e.toBlob?e.toBlob(e=>r(e),t,n):r(null)})}(d,u,o);return!m||m.size>=e.size&&1===l?s(e,i):s(m,u)}catch(l){return s(e,i)}}},28044(e,t,n){n.d(t,{YS:()=>l,hF:()=>d});const r=/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/,o=/\b(email|e-mail|recipient|client|signer|contact|send\s+to|their\s+email|customer)\b/i;function a(e){return e.replace(/^#{1,6}\s+/,"").replace(/\*\*/g,"").trim()}function i(e){const t=a(e);return!!t&&(!!/^---+$/.test(t)||(!!/^#{1,6}[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]/.test(e.trim())||(!!/^From[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*:/i.test(t)||!!/^Date[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*:/i.test(t))))}function s(e){const t=a(e);return!!/^To[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*:/i.test(t)}function l(e){if(!e||"string"!==typeof e)return"";const t=e.replace(/\r\n/g,"\n").split("\n");let n=-1;for(let r=0;r<t.length;r++)if(s(t[r])){n=r;break}if(-1===n)return"";const o=a(t[n]).replace(/^To[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*:[\t-\r \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF]*/i,"").trim();if(o){const e=o.match(r);if(e)return e[0].toLowerCase()}const l=[];for(let r=n+1;r<t.length&&!i(t[r]);r++)l.push(t[r]);const d=l.join("\n").match(r);return d?d[0].toLowerCase():""}function d(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.markdown;const n=function(e){if(!Array.isArray(e))return"";for(const t of e){if(!t||"object"!==typeof t)continue;const e=String(t.question||""),n=String(t.answer||"").trim();if(!n||!o.test(e))continue;const a=n.match(r);if(a)return a[0].toLowerCase()}for(const t of e){if(!t||"object"!==typeof t)continue;const e=String(t.answer||"").trim().match(r);if(e)return e[0].toLowerCase()}return""}(e.clarificationPairs);return n||l(t)}},2859(e,t,n){n.d(t,{DF:()=>o,Eh:()=>h,K1:()=>l,Tx:()=>p,_t:()=>g,ay:()=>s,d5:()=>f,u0:()=>r,uQ:()=>d,vz:()=>a});const r=/\b(sign|signature|e-?sign|e-sign|counterparty|notarize|notary|witness|execute\s+agreement)\b/i,o=/\b(contract|agreement|nda|proposal|statement\s+of\s+work|\bsow\b|legal\s+terms|binding)\b/i,a=/\b(invitation|invite|inviting|networking\s+(event|group|kickoff)|\bkickoff\b|\brsvp\b|casual\s+email|newsletter|thank\s+you\s+note|meeting\s+invite|write\s+an?\s+email|email\s+(to|inviting))\b/i,i=/\b(onboard(?:ing)?|client\s+onboarding|client\s+flow|service\s+onboarding)\b/i,s=new Set(["proposal","contract","sow","nda","one_pager"]);function l(e,t){const n=String(e||""),l=String(t||"auto").toLowerCase();return r.test(n)||o.test(n)||i.test(n)||s.has(l)?"yes":a.test(n)?"no":"letter"===l||"auto"===l?"unsure":"no"}function d(e,t,n){if(!function(e){var t;if(!e)return!1;if(!0===(null===(t=e.enabled)||void 0===t?void 0:t.documentSignatures))return!0;const n=e.enabledDuringStep;return Array.isArray(n)&&n.includes("documentSignatures")}(e))return!1;const r=e.signatureBlocksInDraft;return!0===r||!1!==r&&"yes"===l(t,n)}const c=/\b(both parties|mutual|counter-?sign|we sign|company sign|provider sign|our signature|i sign|signed by both|two signatures|sign(ed)? by (the )?(company|provider|vendor|us))\b/i,u=/\b((client|customer|recipient|counterparty)\s+(signs?|signature|only|to sign|to acknowledge)|send (?:to |for )?(?:the )?(client|customer).{0,40}sign|for (?:the )?(client|customer) to sign)\b/i,m=/\b(two signers|three signers|multiple signers|all parties|each party|every party|witness|third party|signers?:\s*\d)\b/i;function p(e){const t=String(e||"");return!!c.test(t)||!u.test(t)&&(!i.test(t)&&!!o.test(t))}function g(e){return p(e)?"mutual":"client_only"}function h(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;const n=String(e||"");
1return!!m.test(n)||(!(!/\b(2|two|3|three)\b/.test(n)||!/\bsign(er|ature)/i.test(n))||t>2)}function f(e){return e&&"string"===typeof e?e.split("\n").filter(e=>!/^\s*\[\[SIGNATURE(?::\s*.+?)?\]\]\s*$/i.test(e.trim())).join("\n"):e}},12475(e,t,n){function r(e,t){return t&&Array.isArray(e)?e.filter(e=>{return function(e,t){return Boolean(e&&t&&e.organizationId===t)}(e,t)||(r=t,!(!(n=e)||!r)&&n.organizationId!==r&&!0===n.isExternalWorkspace);var n,r}):[]}n.d(t,{jI:()=>r})},49247(e,t,n){n.d(t,{T:()=>r,V:()=>o});const r=140;function o(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:r;const n=(e||"").toString().replace(/\s+/g," ").trim();if(!n)return"";if(n.length<=t)return n;const o=n.slice(0,t);for(let r=o.length-1;r>=Math.floor(.35*t);r--){const e=o[r];if("."===e||"!"===e||"?"===e)return o.slice(0,r+1).trim()}const a=n.match(/[^.!?]+[.!?]+/g);if(null!==a&&void 0!==a&&a.length){let e="";for(const n of a){const r=(e+n).trim();if(!(r.length<=t))break;e=r}if(e.trim())return e.trim()}for(const r of[",",";","\u2014"]){const e=o.lastIndexOf(r);if(e>Math.floor(.45*t)){const t=o.slice(0,e).trim();if(t.length>=20)return t.endsWith(".")?t:"".concat(t,".")}}const i=o.lastIndexOf(" ");if(i>Math.floor(.55*t)){const e=o.slice(0,i).trim();return e.endsWith(".")?e:"".concat(e,".")}return o.trim().endsWith(".")?o.trim():"".concat(o.trim(),".")}}}]);
2//# sourceMappingURL=5739.e53b2eb1.chunk.js.map

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.