PageSourceSearch

https://simplyasking.io/assets/AddPage-DbqwQKDq.js

js simplyasking.io collected 2026-09-24 15:04:56 UTC 293,388 bytes, 17 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-R7rnvG6Y.js","assets/vendor-ui-B6LJVmB2.js","assets/vendor-icons-rWq2ByuV.js","assets/vendor-query-D2dui6iP.js","assets/vendor-supabase-C_jStVHz.js","assets/vendor-react-C26fm6iv.js","assets/vendor-markdown--mR8Btqo.js","assets/index-B-R9e_Lb.css"])))=>i.map(i=>d[i]);
2var Gi=Object.defineProperty;var Vi=(t,s,r)=>s in t?Gi(t,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[s]=r;var _n=(t,s,r)=>Vi(t,typeof s!="symbol"?s+"":s,r);import{r as i,j as e,b as as}from"./vendor-ui-B6LJVmB2.js";import{u as Cs,L as zs,b as Es,c as Ki,N as tr,a as Wi}from"./vendor-react-C26fm6iv.js";import{a as ct,u as He}from"./vendor-query-D2dui6iP.js";import{u as Is,a as Ve,bL as Oe,jz as Yi,aB as Te,s as X,m as W,eV as ma,jA as Kr,E as jn,aD as ar,ai as fa,fk as Hi,$ as ze,jB as Qi,a0 as Je,e1 as Ls,jC as Ji,b as os,fc as Xi,jD as Zi,a3 as nt,dS as Os,bS as eo,ab as Ye,bM as to,jE as so,fr as ro,fs as no,by as rt,cu as ao,cr as io,aH as oo,aa as vr,bH as ha,B as q,R as qt,jF as Rt,jG as sn,gh as pa,e as qs,jH as lo,jI as co,jJ as uo,ah as Gs,jK as mo,f as yt,jL as fo,bt as ir,bu as or,bv as lr,bw as Mt,bx as ga,j as Ue,jM as vt,ae as Ut,bk as xa,jN as Se,jO as Bt,jP as ho,fY as ht,ct as po,cs as Wr,jQ as go,jR as Hs,ax as Nt,ay as kt,az as Ct,h as ws,I as _s,cK as xo,jS as br,jT as yo,jU as vo,f8 as bo,bj as wo,f_ as Ms,Y as ya,jV as _o,U as va,jW as jo,as as So,f0 as ba,a1 as wa,gm as _a,jX as No,X as ko,Q as Co,V as Eo,jY as Io,cf as Or,cJ as cr,cI as To,x as Do,jZ as Ro,j_ as ja,aM as Ao,aj as Po,dV as Lo,cb as Yr,_ as Fo,fl as Sa,dP as Oo,ag as $o,F as Mo,fZ as Uo,j$ as Bo,gn as zo,fi as qo,k0 as Sn,k1 as Nn,k2 as Go,j8 as Vo,k3 as Ko}from"./index-R7rnvG6Y.js";import{P as rn}from"./PageHeaderV2-BWKQCVLz.js";import{P as Na}from"./PageShell-U4mYLSwO.js";import{A as Wo,a as Yo}from"./ActivityTray-AVsKxjGC.js";import{u as wr}from"./usePageTitle-6bWRZ9w6.js";import{g as ns,c as ms,p as ka,s as Ho,e as Qo,D as Jo,P as Xo,f as $r,u as Zo,V as el}from"./PreviewDrawer-B9hoza9d.js";import{b as tl}from"./useExclusionPatterns-BtxViEjz.js";import{u as sl}from"./useOrgDocumentTypes-DIU1OISI.js";import{c as rl}from"./markdownToHtml-bJdoD_VG.js";import{e as nl,b as al,r as il,T as ol,E as ll}from"./EnhanceDiffPreview-Cn55bSHb.js";import{P as cl,V as dl,c as Qs,M as dr,U as ul,a as ml,i as ur,g as Hr,b as kn,d as fl,E as Cn,e as hl,h as Ca,f as Qr,I as pl,j as gl,k as En,l as In}from"./upload-helpers-BgUL4JBF.js";import{D as xl}from"./DuplicateBlockDialog-DAEfVXWN.js";import{C as yl,a as vl,b as bl}from"./collapsible-fGPlj_fF.js";import{T as Et,aI as nn,an as Vs,F as ps,aZ as Ss,cA as wl,e as Ea,C as gs,A as Ia,b as it,g as js,Y as Ta,ax as Da,bg as Ra,a_ as mr,aH as _l,a$ as Aa,cj as jl,l as an,dj as Pa,b0 as on,ew as Sl,as as at,ar as Zt,cM as Nl,cK as Jr,ex as La,b7 as Ts,ba as Us,ey as kl,i as fs,aV as sr,bd as Cl,j as Tn,av as _r,aX as Ns,aK as El,aW as jr,bH as ln,aQ as rr,bm as Xr,c4 as Sr,m as cn,cl as Fa,cu as Oa,ca as Js,q as Il,a1 as Tl,a as Dl,ez as Rl,k as Dn,az as Al,cF as Zr,f as Bs,bV as Pl,am as fr,ae as Ll,aS as Fl,ay as Ol,w as $l,R as Ml}from"./vendor-icons-rWq2ByuV.js";import{g as $a,u as dn,c as Ks,d as Ma,a as Ul,s as Rn,b as Ua,e as Bl,f as zl}from"./useConnections-CMqoDIbB.js";import{i as ql}from"./environment-C-Sh0xnc.js";import{u as Gl}from"./useAwaitingReviewCount-AfWpUJpt.js";import{C as Ba}from"./ConfirmDeleteDialog-DlJct6SK.js";import{s as An}from"./page-layout.module-DXbwLEsb.js";import{g as Vl}from"./chip-variants-B0dTv9Bp.js";import{T as za,a as qa,b as hr,c as Jt,d as Ga,e as Xt}from"./table-CVUT1hH_.js";import{D as Pn}from"./DirectoryWorkbench-DnYuqtPH.js";import{P as Kl}from"./PaneSection-CGhwOoIG.js";import{P as Wl}from"./PaneTabs-C6gp_96X.js";import{C as Vt}from"./checkbox-CI_DjiDO.js";import{c as Yl}from"./chunk-ids-gwsV1vW0.js";import{P as Hl}from"./PlatformListToolbar-DfyugpVD.js";import{u as un}from"./useDepartments-ChrHhU59.js";import{b as Ql,a as Jl,D as Xl}from"./TagsEditPopover-Cr6ZmDRJ.js";import{D as Nr}from"./DepartmentSelector-BHvt5JjG.js";import{m as is,A as Va}from"./vendor-motion-C442iPuo.js";import{c as Zl}from"./useBrainCenterCounts-K3lPlVjl.js";import"./index-BlrzN-JS.js";import{k as Xs}from"./useKnowledgeGraph-CEy2-RVK.js";import"./vendor-supabase-C_jStVHz.js";import"./vendor-markdown--mR8Btqo.js";import"./library-folder-DTmnnpxM.js";import"./selection-checkbox-vdJkcbva.js";import"./PanelMenu-CRN3hYVV.js";import"./CountPill-DsniJx7Y.js";import"./subDays-DcaTI9yc.js";import"./useUserDepartments-BDpxvCMG.js";import"./useFactCandidates-CCcPO6n-.js";import"./useGraphEntityTypeCounts-vAAfGEu2.js";import"./brain-center-BI756TWz.js";import"./with-selector-BJR62iaY.js";
2const zt={PENDING:"pending",UPLOADING:"uploading",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},pr=new Set(["add","alter","and","as","asc","backup","begin","between","break","browse","bulk","by","cascade","case","check","checkpoint","close","clustered","coalesce","collate","column","commit","compute","constraint","contains","containstable","continue","convert","create","cross","current","current_date","current_time","current_timestamp","current_user","cursor","database","dbcc","deallocate","declare","default","delete","deny","desc","disk","distinct","distributed","double","drop","dummy","dump","else","end","errlvl","escape","except","exec","execute","exists","exit","fetch","file","fillfactor","for","foreign","freetext","freetexttable","from","full","function","goto","grant","group","having","holdlock","identity","identity_insert","identitycol","if","in","index","inner","insert","intersect","into","is","join","key","kill","left","like","lineno","load","national","nocheck","nonclustered","not","null","nullif","of","off","offsets","on","open","opendatasource","openquery","openrowset","openxml","option","or","order","outer","over","percent","plan","precision","primary","print","proc","procedure","public","raiserror","read","readtext","reconfigure","references","replication","restore","restrict","return","revert","revoke","right","rollback","rowcount","rowguidcol","rule","save","schema","securityaudit","select","session_user","set","setuser","shutdown","some","statistics","system_user","table","tablesample","textsize","then","to","top","tran","transaction","trigger","truncate","try_convert","tsequal","union","unique","unpivot","update","updatetext","use","user","values","varying","view","waitfor","when","where","while","with","within group","write","writetext"]);function ec(t){const s=t.lastIndexOf("."),r=s>0?t.slice(0,s):t,n=s>0?t.slice(s+1).toLowerCase():"";let a=r.trim().replace(/\s+/g,"-").replace(/[^\w-]/g,"").toLowerCase();return a=a.split(/-/).map(g=>pr.has(g)?`file-${g}`:g).join("-"),pr.has(a)&&(a=`file-${a}`),n?`${a}.${n}`:a}function tc(t){const{orgType:s,userId:r,filename:n,orgId:a}=t;if(s==="business"&&!a)throw new Error("Missing orgId for business org");if(s==="internal"&&!a)throw new Error("Missing orgId for internal org");const o=s==="personal"?`personal/${r}`:s==="business"?`business/${a}`:`internal/${a}`,d=ec(n),g=crypto.randomUUID(),c=`${o}/${g}-${d}`;let u=c;u=c.split("/").map(m=>{let f=m;for(const p of pr){const v=p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),y=new RegExp(`(^|[^a-z0-9_])${v}([^a-z0-9_]|$)`,"gi");y.test(f)&&(f=f.replace(y,(I,M,k)=>`${M}file-${p}${k}`))}return f}).join("/");for(const m of pr){const f=m.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),p=new RegExp(`(^|[^a-z0-9_])${f}([^a-z0-9_]|$)`,"gi");p.test(u)&&(u=u.replace(p,(v,y,I)=>`${y}file-${m}${I}`))}return u}const Ln=2,Fn=3,sc=2e3,rc=500;function nc(t,s){return Yi(t,"uploading")}function ac(t){const s=t instanceof Error?t.message:String(t);return/Failed to fetch|NetworkError|Load failed|ERR_CONNECTION|ERR_NAME_NOT_RESOLVED|AbortError/i.test(s)}function ic(){const[t,s]=i.useState(!1),[r,n]=i.useState([]),a=ct(),{user:o}=Is(),{orgId:d,org:g}=Ve(),c=(g==null?void 0:g.org_type)||Oe.PERSONAL,u=i.useRef(!1),h=async(f,p,v,y,I=M=>M())=>{var M,k,S,T,O;try{const w=tc({orgType:c,userId:p.user.id,filename:f.name,orgId:v}),b=f.name.toLowerCase().split(".").pop();if(["mp4","mov","webm","mkv","avi","wmv","flv"].includes(b||""))throw new Error("Videos must be added via URL Reference. Paste a share/view URL and submit.");const Q=["mp3","m4a","wav","ogg","flac","aac","wma"].includes(b||""),re=25*1024*1024;if(Q&&f.size>re){const U=new Error(`Audio Too Large (25MB limit): ${f.name} is ${(f.size/1048576).toFixed(2)}MB. Please upload a smaller file or split it into parts.`);throw U.isSizeError=!0,U.fileName=f.name,U.fileSize=f.size,U}let{error:K}=await X.storage.from("kb-uploads").upload(w,f,{cacheControl:"3600",contentType:f.type||void 0,upsert:!1});if(K&&(K.statusCode==="409"||(M=K.message)!=null&&M.includes("already exists")||(k=K.message)!=null&&k.includes("duplicate"))&&(Te("[useIngest] File already exists, removing and re-uploading:",w),await X.storage.from("kb-uploads").remove([w]),K=(await X.storage.from("kb-uploads").upload(w,f,{cacheControl:"3600",contentType:f.type||void 0,upsert:!1})).error),K)throw K;const D={org_type:c,docTitle:(y==null?void 0:y.docTitle)||f.name,docSummary:(y==null?void 0:y.docSummary)||void 0,storagePath:w,orgId:v,departmentId:(y==null?void 0:y.departmentId)??null,...y!=null&&y.libraryFolderId?{library_folder_id:y.libraryFolderId}:{}
2,inlineText:y==null?void 0:y.inlineText,tags:(y==null?void 0:y.tags)??[],...y!=null&&y.docType?{doc_type:y.docType}:{},...(y==null?void 0:y.defer_duplicate_check)!==void 0?{defer_duplicate_check:y.defer_duplicate_check}:{},...ms(f)?{upload_folder:ms(f)}:{},...y!=null&&y.skip_duplicate_check?{skipDuplicateCheck:!0}:{},...y!=null&&y.resolved_department_id?{resolved_department_id:y.resolved_department_id}:{}};let E;try{E=await I(async()=>{for(let U=0;;U++)try{return await Kr(D)}catch(Z){if(Z instanceof jn||U>=Fn||!ac(Z))throw Z;const le=sc*Math.pow(2,U);Te(`[useIngest] Network error uploading "${f.name}", retry ${U+1}/${Fn} in ${le}ms`),await new Promise(De=>setTimeout(De,le))}})}catch(U){if(U instanceof jn){const Z=U.response;W("useIngest",Z,"ingest-upload failed:");const le=Z.duplicate===!0||((S=Z.message)==null?void 0:S.toLowerCase().includes("duplicate"))||((T=Z.message)==null?void 0:T.toLowerCase().includes("already exists"));if(U.status===409&&le){const ye=(O=Z.message)==null?void 0:O.match(/"([^"]+)"/),pe=(ye==null?void 0:ye[1])||Z.existing_title||"existing document",de=new Error(Z.message||"DUPLICATE_BLOCKED");throw Te("[useIngest] Creating DUPLICATE_BLOCKED error with objectKey:",w),de.isDuplicate=!0,de.data={action_required:"duplicate_blocked",duplicate:!0,duplicate_type:Z.duplicate_type||"exact",existing_doc_id:Z.existing_doc_id||"",existing_title:pe,message:Z.message||"",file:f,storagePath:w,extracted_text:Z.extracted_text||null},de}const De=Z.error||`Upload failed (${U.status})`,fe=new Error(De);throw fe.statusCode=U.status,fe}throw U}if(Te("[useIngest] ingest-upload response:",{responseData:E}),E.action_required==="update_or_version"){Te("[useIngest] Detected update_or_version, throwing special error"),Te("[useIngest] Creating UPDATE_OR_VERSION_REQUIRED error with objectKey:",w);const U=new Error("UPDATE_OR_VERSION_REQUIRED");throw U.isUpdateOrVersion=!0,U.data={action_required:"update_or_version",existing_doc_id:E.existing_doc_id||"",existing_title:E.existing_title||"",existing_version_number:E.existing_version_number||1,content_hash:E.content_hash||"",extracted_text:E.extracted_text||null,file:f,storagePath:w},U}const N=E.doc_id||null,L=E.job_id||null;if(!N)throw new Error("Upload was not acknowledged. Please try again.");return L||Te("[useIngest] Warning: job_id not in response, processing may be deferred to worker"),{success:!0,file:f,objectKey:w,documentId:N||void 0,jobId:L||void 0,isAudio:Q}}catch(w){return{success:!1,file:f,error:w instanceof Error?w:String(w)}}},x=async(f,p,v,y)=>{const I=new Array(f.length);let M=0;const k=async()=>{const T=M++;if(T>=f.length)return;const O=await v(f[T],T);I[T]=O,M<f.length&&await new Promise(w=>setTimeout(w,rc)),await k()},S=Array(Math.min(p,f.length)).fill(null).map(()=>k());return await Promise.all(S),I};return{uploading:t,uploadProgress:r,uploadFiles:async(f,p)=>{var b,P,l,$,Q,re;if(u.current)return Te("[useIngest] Upload already in progress"),[];const v=d;if(!v){const K=new Error("No organization found. Please ensure you are properly authenticated.");throw(b=p==null?void 0:p.onError)==null||b.call(p,K),K}const{data:{session:y},error:I}=await X.auth.getSession();if(I)throw W("useIngest",I,"Session error:"),new Error("Authentication failed: "+I.message);if(!y)throw new Error("No active session found. Please sign in again.");const M=Array.from(f),k=(p==null?void 0:p.continueOnError)??M.length>1,S=M.map(K=>({entryId:ns(K),fileName:K.name,status:zt.PENDING}));let T=S;const O=(K,D)=>{var E;T=T.map((N,L)=>L===K?{...N,...D}:N),n(T),(E=p==null?void 0:p.onProgress)==null||E.call(p,T)};n(S),(P=p==null?void 0:p.onProgress)==null||P.call(p,S),s(!0),u.current=!0,Te(`[useIngest] Starting parallel upload of ${M.length} files (${Ln} concurrent)`);const w=Date.now();try{const K=M.length>1;let D=p;if(K){const C={defer_duplicate_check:(p==null?void 0:p.defer_duplicate_check)??!0};if((c===Oe.BUSINESS||c===Oe.INTERNAL)&&!(p!=null&&p.departmentId)){const{data:A,error:B}=await X.rpc("get_pending_review_department_id",{p_org_id:v});if(B&&W("useIngest",B,"Preflight dept lookup failed:"),A)C.resolved_department_id=A;else{const{data:te,error:he}=await X.rpc("ensure_pending_review_department",{p_org_id:v});he&&W("useIngest",he,"Preflight dept create failed:"),te&&(C.resolved_department_id=te)}Te(`[useIngest] Batch preflight: resolved department ${(l=C.resolved_department_id)==null?void 0:l.substring(0,8)}...`)}D={...p,...C},Te(`[useIngest] Batch mode: ${M.length} files, duplicate checks ${D.defer_duplicate_check?"deferred":"synchronous"}`)}const E=[],N=[],L=[],U=!1;let Z=!1,le=null;const De=[],fe=M.map((C,A)=>new Promise(B=>{De[A]=B})),ye=await x(M,Ln,async(C,A)=>{var te,he,ue;O(A,{status:zt.UPLOADING});const B=await h(C,y,v,{...D,...(te=p==null?void 0:p.fileOptions)==null?void 0:te.call(p,C)},(p==null?void 0:p.defer_duplicate_check)===!1?async Ae=>(A>0&&await fe[A-1],Ae()):void 0).finally(async()=>{(p==null?void 0:p.defer_duplicate_check)===!1&&A>0&&await fe[A-1],De[A]()});return O(A,{status:B.success?zt.COMPLETED:zt.FAILED,skipped:B.error instanceof Error&&("isDuplicate"in B.error&&B.error.isDuplicate===!0||"isUpdateOrVersion"in B.error&&B.error.isUpdateOrVersion===!0),documentId:B.documentId,error:typeof B.error=="string"?B.error:(he=B.error)==null?void 0:he.message}),(ue=p==null?void 0:p.onFileComplete)==null||ue.call(p,B),B});for(const C of ye)if(C.success)C.objectKey&&E.push(C.objectKey),C.documentId&&N.push(C.documentId),C.jobId&&L.push(C.jobId),C.isAudio&&(Z=!0);else{if(!le&&C.error&&(le=C.error instanceof Error?C.error:new Error(C.error)),!k&&C.error){const B=typeof C.error=="string"?C.error:C.error.message,te=C.error instanceof Error&&"isUpdateOrVersion"in C.error?C.error.isUpdateOrVersion:!1;throw Te("[useIngest] Throwing error for single file:",B,"isUpdateOrVersion:",te),C.error instanceof Error?C.error:new Error(C.error)}const A=typeof C.error=="string"?C.error:($=C.error)==null?void 0:$.message;W("useIngest",C.error,`File "${C.file.name}" failed:`,A)}const pe=((Date.now()-w)/1e3).toFixed(1),de=ye.filter(C=>C.success).length,F=ye.filter(C=>!C.success).length;if(Te(`[useIngest] Parallel upload complete: ${de} succeeded, ${F} failed in ${pe}s`),de>0&&((Q=p==null?void 0:p.onSuccess)==null||Q.call(p,{hasVideo:U,hasAudio:Z,uploadedPaths:E,documentIds:N,jobIds:L})),de===0&&le&&(!k||!(p!=null&&p.onFileComplete)))throw le;const ie=new URLSearchParams(window.location.search).get("fulfill_request");let oe=ie;if(!oe)try{const C=sessionStorage.getItem("pendingResourceRequestId");if(C){const A=JSON.parse(C);
2A.id&&A.ts&&Date.now()-A.ts<6e5?oe=A.id:sessionStorage.removeItem("pendingResourceRequestId")}}catch{oe=sessionStorage.getItem("pendingResourceRequestId")}return oe&&o&&N.length>0&&setTimeout(()=>void(async()=>{try{const{data:C,error:A}=await X.from("kb_documents").select("id, title").in("id",N).eq("org_id",v).eq("created_by",o.id).order("created_at",{ascending:!1}).limit(1);if(!A&&C&&C.length>0){const B=C[0],{data:te,error:he}=await X.from("resource_requests").select("user_id, org_id, linked_resource_id").eq("id",oe).single();if(!he&&te&&!te.linked_resource_id){const ue=new Date().toISOString(),{data:Ae,error:Ce}=await X.from("resource_requests").update({linked_resource_id:B.id,linked_resource_title:B.title,status:ma.COMPLETED,resolution_type:"created_new",fulfilled_by:o.id,fulfilled_at:ue,resolved_at:ue,resolved_by:o.id}).eq("id",oe).select("id").single();if(Ce===null&&(Ae==null?void 0:Ae.id)===oe){if(await X.from("resource_request_notifications").insert({request_id:oe,user_id:te.user_id,notification_type:"resource_linked",message:`Your requested resource "${B.title}" has been created!`}),te.org_id&&X.rpc("cross_resolve_gap_request",{p_doc_id:B.id,p_user_id:o.id,p_org_id:te.org_id}).then(()=>{},()=>{}),a.invalidateQueries({queryKey:["admin-resource-requests"]}),a.invalidateQueries({queryKey:["resource-requests"]}),a.invalidateQueries({queryKey:["notifications"]}),sessionStorage.removeItem("pendingResourceRequestId"),ie){const xe=new URL(window.location.href);xe.searchParams.delete("fulfill_request"),window.history.replaceState({},"",xe.toString())}}else throw new Error("The primary request update was not acknowledged")}else sessionStorage.removeItem("pendingResourceRequestId")}}catch(C){W("useIngest",C,"Error auto-linking resource to request:")}})(),2e3),E}catch(K){throw(re=p==null?void 0:p.onError)==null||re.call(p,K instanceof Error?K:new Error("Unknown error")),K}finally{s(!1),u.current=!1}}}}function oc(t){return new Promise((s,r)=>{const n=[],a=()=>{t.readEntries(o=>{o.length===0?s(n):(n.push(...o),a())},o=>r(o))};a()})}function lc(t){return new Promise((s,r)=>{t.file(s,r)})}async function Ka(t,s,r=""){if(t.isFile){const n=await lc(t);return n.name.startsWith(".")?[]:(s&&Ho(n,{...s,relative_path:`${r}${n.name}`}),[n])}if(t.isDirectory){const n=t.createReader(),a=await oc(n),o=s??{root_id:crypto.randomUUID(),root_name:t.name};return(await Promise.all(a.map(g=>Ka(g,o,`${r}${t.name}/`)))).flat()}return[]}async function cc(t){const s=t.dataTransfer.items;if(s&&s.length>0&&"webkitGetAsEntry"in s[0]){const r=[];for(let a=0;a<s.length;a++){const o=s[a].webkitGetAsEntry();o&&r.push(o)}return(await Promise.all(r.map(a=>Ka(a)))).flat()}return ka(Array.from(t.dataTransfer.files))}const Mr={"purchase order":"purchase_order","purchase orders":"purchase_order",po:"purchase_order",invoice:"invoice",invoices:"invoice",receipt:"receipt",receipts:"receipt","shipping order":"shipping_order","shipping orders":"shipping_order","distribution instructions":"distribution_instructions","distribution instruction":"distribution_instructions","compliance form":"compliance_form","compliance forms":"compliance_form","inspection report":"inspection_report","inspection reports":"inspection_report","work order":"work_order","work orders":"work_order"},dc=new Set(["po","rfq","sow","nda","msa","bol","coa","sds","msds","rma","wo","inv","rcpt","sla","rfp","rfi"]);function uc(t){return t.replace(/\.[^.]+$/,"").toLowerCase().trim()}function On(t){return t.replace(/\d{1,4}[-/]\d{1,2}[-/]\d{1,4}/g,"").replace(/\b\d+\b/g,"").replace(/\s+/g," ").trim()}function mc(t,s){const r=On(t),n=On(s),a=r.split(/[\s_-]+/).filter(Boolean),o=n.split(/[\s_-]+/).filter(Boolean),d=a.filter(f=>o.includes(f)),g=d.length===1&&dc.has(d[0]);if(d.length<2&&!g||!g&&(a.length<2||o.length<2))return null;const c=d.join(" "),u=a.indexOf(d[0]),h=o.indexOf(d[0]),x=a.slice(0,u).join(" "),m=o.slice(0,h).join(" ");return!x&&!m&&!g?null:{pattern:c,prefixA:x,prefixB:m}}function fc(t){const s=t.toLowerCase();if(Mr[s])return Mr[s];for(const[r,n]of Object.entries(Mr))if(s.includes(r)||r.includes(s))return n;return null}function hc(t,s){return s&&ar[s]?ar[s]:t.split(" ").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function pc(t){if(t.length<2)return{families:[],ungrouped:[...t]};const s=t.map(g=>uc(g.name)),r=new Map;for(let g=0;g<t.length;g++)for(let c=g+1;c<t.length;c++){const u=mc(s[g],s[c]);if(!u)continue;const h=u.pattern;r.has(h)||r.set(h,{files:new Set,prefixes:new Set});const x=r.get(h);x.files.add(g),x.files.add(c),u.prefixA&&x.prefixes.add(u.prefixA),u.prefixB&&x.prefixes.add(u.prefixB)}const n=new Set,a=[],o=[...r.entries()].sort((g,c)=>c[1].files.size-g[1].files.size);for(const[g,c]of o){const u=[...c.files].filter(x=>!n.has(x));if(u.length<2)continue;const h=fc(g);a.push({pattern:g,label:hc(g,h),docType:h,files:u.map(x=>t[x]),prefixes:[...c.prefixes]}),u.forEach(x=>n.add(x))}const d=t.filter((g,c)=>!n.has(c));return{families:a,ungrouped:d}}function gc(t,s){const r=He({queryKey:["infer-doc-type",t,s],queryFn:async()=>
2{if(!t||!s)return null;const{data:n,error:a}=await X.rpc("infer_doc_type_from_exclusion_pattern",{p_org_id:t,p_title:s});return a?(fa(`[useInferDocType] RPC error for "${s}":`,a.message),null):n&&typeof n=="string"&&Hi(n)?n:null},enabled:!!t&&!!s&&s.length>3,staleTime:3e4,gcTime:6e4});return{suggestedType:r.data??null,isLoading:r.isLoading}}function xc(){const{orgId:t}=Ve(),{data:s=[],isLoading:r}=He({queryKey:["tag-suggestions",t],queryFn:async()=>{if(!t)return[];const{data:{user:a}}=await X.auth.getUser();if(!a)return[];const{data:o,error:d}=await X.rpc("get_popular_tags",{p_org_id:t,p_user_id:a.id,p_limit:10});return d?(fa("[useTagSuggestions] RPC failed:",d.message),[]):!o||!Array.isArray(o)?[]:o.map(g=>({tagName:g.tag_name,docCount:g.doc_count,isUserRecent:g.is_user_recent}))},enabled:!!t,staleTime:300*1e3,gcTime:600*1e3});return{suggestions:[...s].sort((a,o)=>a.isUserRecent!==o.isUserRecent?a.isUserRecent?-1:1:o.docCount-a.docCount).slice(0,5).map(a=>a.tagName),isLoading:r}}function yc({initialMode:t="idle",libraryFolderId:s,uploadDestinationBlocked:r=!1,onCreateText:n,onUploadComplete:a,onModeChange:o,variant:d="compact"}){const g=Cs(),{orgId:c,org:u}=Ve(),{user:h}=Is(),{toast:x}=ze(),m=ct(),f=(u==null?void 0:u.org_type)||Oe.PERSONAL,{suggestions:p}=xc(),[v,y]=i.useState(t),I=i.useRef(!0),M=i.useRef(!1),[k,S]=i.useState(!1),[T,O]=i.useState(!1),w=i.useRef(!1),[b,P]=i.useState(!1),[l,$]=i.useState("upload"),[Q,re]=i.useState(0),[K,D]=i.useState(!1),[E,N]=i.useState(""),[L,U]=i.useState([]),[Z,le]=i.useState(""),[De,fe]=i.useState(!1),[ye,pe]=i.useState(""),[de,F]=i.useState(""),[Y,ie]=i.useState([]),[oe,C]=i.useState(""),[A,B]=i.useState(""),[te,he]=i.useState(""),[ue,Ae]=i.useState(null),[Ce,xe]=i.useState(!1),[$e,se]=i.useState(0),ke=i.useRef(null),Ee=i.useRef(null),[Xe,bt]=i.useState(null),[Qe,dt]=i.useState(null),[Kt,pt]=i.useState(!1),[Ze,Ie]=i.useState(""),[ot,Be]=i.useState(!1),[Wt,wt]=i.useState(!1),[_t,At]=i.useState(!1),[gt,xt]=i.useState(null),[jt,ut]=i.useState(!1),[Pt,It]=i.useState(null),[G,ne]=i.useState(null),[ce,J]=i.useState(new Map),[ve,Pe]=i.useState(!1),[qe,mt]=i.useState(()=>{const R=sessionStorage.getItem("uploadDocTypePreference");return R==="null"||!R?null:R}),[et,Tt]=i.useState(null),[Yt,ft]=i.useState(!1),[j,ee]=i.useState(!1),[me,Le]=i.useState(!1),[tt,Lt]=i.useState([]),[Ht,es]=i.useState(!1),[ge,Ft]=i.useState(null),[Ke,Qt]=i.useState(null),Ds=i.useRef(null),Dr=i.useRef(null),{uploadFiles:ts,uploadProgress:Ws}=ic(),xs=tl(),{data:ys,isLoading:vn,error:bn}=sl(),Rr=ys&&ys.length>0?ys.map(R=>({slug:R.slug,label:R.label,mode:R.mode})):void 0,Ys=L.length===1?L[0].name:null,{suggestedType:ls}=gc(c,Ys);i.useEffect(()=>{if(ls&&qe===null&&L.length===1){mt(ls);const R=new Map;R.set(ns(L[0]),ls),J(R)}},[ls,qe,L]),i.useEffect(()=>{if(v!=="idle"||E.length>0)return;const R=setInterval(()=>{D(!0),setTimeout(()=>{re(V=>(V+1)%cl.length),D(!1)},400)},4e3);return()=>clearInterval(R)},[v,E]),i.useEffect(()=>{if(v!=="ai-create")return;const R=sessionStorage.getItem("aiCreationContext");if(R)try{const V=JSON.parse(R),ae=[];V.resourceType&&V.userMessage?ae.push(`Create a ${V.resourceType} about: ${V.userMessage}`):V.userMessage&&ae.push(V.userMessage),V.additionalInstructions&&ae.push(`
3Additional instructions: ${V.additionalInstructions}`),ae.length>0&&he(ae.join("")),sessionStorage.removeItem("aiCreationContext")}catch{sessionStorage.removeItem("aiCreationContext")}},[v]),i.useEffect(()=>{if(I.current){I.current=!1;return}t!==v&&(M.current=!0,y(t),t==="idle"?$("upload"):t==="url"?$("url"):t==="text"?$("text"):t==="file"&&$("file"))},[t]),i.useEffect(()=>{if(M.current){M.current=!1;return}const R=v!=="idle";o==null||o(v,R)},[v,o]);const Rs=i.useCallback(()=>{se(0),ke.current=setInterval(()=>{se(R=>{var V;return R+1>=dl&&((V=Ee.current)==null||V.stopRecording()),R+1})},1e3)},[]),Ot=i.useCallback(()=>{ke.current&&(clearInterval(ke.current),ke.current=null)},[]);i.useEffect(()=>()=>{ke.current&&clearInterval(ke.current)},[]),i.useEffect(()=>{if(v==="voice"&&!Ce&&!b){const R=setTimeout(()=>{(async()=>{var ae;await((ae=Ee.current)==null?void 0:ae.startRecording())&&(xe(!0),Rs())})()},300);return()=>clearTimeout(R)}},[v]);const Me=i.useCallback(()=>{var R;w.current||((R=Ee.current)==null||R.stopRecording(),y("idle"),N(""),U([]),le(""),pe(""),F(""),ie([]),C(""),B(""),he(""),Ae(null),xe(!1),se(0),$("upload"),Ot(),wt(!1),Ft(null),Tt(null),Qt(null),ne(null),J(new Map),Pe(!1),mt(null),sessionStorage.removeItem("uploadDocTypePreference"),bt(null),dt(null),pt(!1),Ie(""),setTimeout(()=>{var V;return(V=Ds.current)==null?void 0:V.focus()},100))}
3,[]),Ar=i.useCallback(()=>{if(ft(!1),et){Tt(null),x({title:"Cancelled",description:"Document not created."});return}if(Ft(null),ge){const R=L.filter(V=>V.name!==ge.newFileName);U(R),R.length===0&&F("")}x({title:"Upload Blocked",description:"Duplicate upload cancelled.",variant:"warning"})},[ge,et,L,x]),_=i.useCallback(()=>{ge&&(ft(!1),setTimeout(()=>{ee(!0)},100))},[ge]),z=i.useCallback(async()=>{Te("[CommandSurface] handleCreateVersionFromDuplicate called");const R=ge||Ke,V=(ge==null?void 0:ge.file)||L[0];if(!(R!=null&&R.existingDoc)){W("CommandSurface",new Error("No candidate for version creation")),x({title:"Error",description:"No document selected for version creation",variant:"destructive"});return}const ae=(ge==null?void 0:ge.fileData.storagePath)||(Ke==null?void 0:Ke.fileData.source_ref.path);if(!ae){W("CommandSurface",new Error("Unexpected: storagePath missing despite type guarantees")),x({title:"Error",description:"An unexpected error occurred. Please try again.",variant:"destructive"});return}try{const be={existing_doc_id:R.existingDoc.id,file_data:{content_hash:(Ke==null?void 0:Ke.fileData.content_hash)||null,file_size:(V==null?void 0:V.size)||0,source_ref:{path:ae}},title:de||(ge==null?void 0:ge.newFileName)||(V==null?void 0:V.name),tags:Y,summary:null,extracted_text:(Ke==null?void 0:Ke.fileData.extracted_text)||(ge==null?void 0:ge.fileData.extractedText)||null};Te("[CommandSurface] Calling create-version with:",be);const Fe=await Qi(be);if(Te("[CommandSurface] create-version response:",Fe),!Fe.success)throw new Error("Version creation returned unsuccessful");Fe.warning?x({title:"Version Created with Warning",description:`Version ${Fe.version_number} created. ${Fe.warning}`,variant:"default"}):x({title:"New Version Created",description:`Version ${Fe.version_number} created successfully.`,variant:"success"}),ee(!1),ft(!1),Ft(null),Qt(null),Me(),m.invalidateQueries({queryKey:["recent-personal-ingest"]}),m.invalidateQueries({queryKey:["processing-steps",c]}),m.refetchQueries({queryKey:["processing-steps",c]}),a==null||a()}catch(be){W("CommandSurface",be,"Error creating version:"),Je(x,be,"creating version")}},[ge,Ke,L,de,Y,x,Me,m,c,a]),H=i.useCallback(async()=>{const R=ge||Ke,V=(ge==null?void 0:ge.file)||L[0],ae=(ge==null?void 0:ge.fileData.storagePath)||(Ke==null?void 0:Ke.fileData.source_ref.path);if(!(!R||!ae)&&!r)try{ee(!1),O(!0),await Kr({storagePath:ae,...s?{library_folder_id:s}:{},...V&&ms(V)?{upload_folder:ms(V)}:{},docTitle:de||(ge==null?void 0:ge.newFileName)||(V==null?void 0:V.name)||"",org_type:f,tags:Y,orgId:c??void 0,departmentId:f===Oe.BUSINESS||f===Oe.INTERNAL?ue:null,duplicate_action:"new_version"}),x({title:"Upload successful",description:"Document uploaded as a new file.",variant:"success"}),Ft(null),Qt(null),Me(),a==null||a(),Ls(m,"documents"),m.invalidateQueries({queryKey:["processing-steps",c]})}catch(be){W("CommandSurface",be,"Error uploading as new:"),Je(x,be,"uploading")}finally{O(!1)}},[ge,Ke,L,s,r,de,Y,c,f,ue,x,Me,a,m]),je=i.useCallback(()=>{const R=(ge==null?void 0:ge.existingDoc.id)??(et==null?void 0:et.existingDoc.id);R&&(g(`/library/${R}`),ft(!1),Ft(null),Tt(null))},[ge,et,g]),st=i.useCallback(()=>{if(et){ft(!1),O(!0),(async()=>{try{await n(et.newTitle,et.content,et.tags,!0,{skip_duplicate_check:!0}),Me()}catch(R){const V=R instanceof Error?R.message:"An error occurred";x({title:"Publish failed",description:V,variant:"destructive"})}finally{O(!1),Tt(null)}})();return}ge&&(ft(!1),setTimeout(()=>{Le(!0)},100))},[ge,et,n,Me,x]),Ge=i.useCallback(async()=>{if(!r){if(Le(!1),L.length>0){O(!0);try{const R=L[0];await ts([R],{libraryFolderId:s,docTitle:de||Qs(R.name),docSummary:A||void 0,tags:Y,orgId:c,departmentId:f===Oe.BUSINESS||f===Oe.INTERNAL?ue:null,skip_duplicate_check:!0,onSuccess:()=>{x({title:"Upload successful",description:`${de||R.name} has been uploaded.`,variant:"success"}),Me(),a==null||a(),Ls(m,"documents"),m.invalidateQueries({queryKey:["processing-steps",c]})}})}catch(R){const V=R instanceof Error?R.message:"An error occurred";x({title:"Upload failed",description:V,variant:"destructive"})}finally{O(!1)}}Ft(null)}},[L,s,r,de,A,Y,c,f,ue,ts,x,Me,a,m]),Re=i.useCallback(()=>{const R=oe.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");R&&!Y.includes(R)&&Y.length<dr&&(ie([...Y,R]),C(""))},[oe,Y]),$t=i.useCallback(R=>{const V=R.trim().toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"");V&&!Y.includes(V)&&Y.length<dr&&ie([...Y,V])},[Y]),ss=i.useCallback(R=>{var Fe;if(w.current||!R||R.length===0)return;const V=ka(Array.from(R)),ae=[],be=new Map;for(const lt of V){const we=((Fe=lt.name.split(".").pop())==null?void 0:Fe.toLowerCase())||"";
3ul.includes(we)?be.set(we,(be.get(we)||0)+1):ae.push(lt)}for(const[lt]of be){const we=ml[lt];we&&x({title:we.title,description:we.description,duration:8e3})}if(ae.length!==0){if(U(ae),ae.length===1?F(Qs(ae[0].name)):F(""),ae.length>=2){const lt=pc(ae);lt.families.length>0?ne(lt):ne(null)}else ne(null);J(new Map),$("file"),y("file")}},[x]),_i=i.useCallback(R=>{const V=new Map;for(const ae of R.confirmed){if(ae.docType)for(const be of ae.files)V.set(ns(be),ae.docType);ae.files.length>=2&&xs.mutate({titleA:ae.files[0].name,titleB:ae.files[1].name})}J(V),ne(null),Pe(!0)},[xs]),ji=i.useCallback(()=>{ne(null)},[]),Si=i.useCallback(R=>{if(mt(R),R?sessionStorage.setItem("uploadDocTypePreference",R):sessionStorage.removeItem("uploadDocTypePreference"),R&&L.length>0){const V=new Map;for(const ae of L)V.set(ns(ae),R);J(V),Pe(!0)}else R||(J(new Map),Pe(!1))},[L]),Ni=i.useCallback(async R=>{if(w.current||r||L.length===0||!c||!(h!=null&&h.id))return;w.current=!0;const V=L.length,ae=V>1;O(!0),It(ae?{current:0,total:V,failedCount:0}:null);let be=!1;const Fe=[];try{const lt=new Map;await ts(L,{libraryFolderId:s,docSummary:A||void 0,tags:Y,orgId:c,departmentId:f===Oe.BUSINESS||f===Oe.INTERNAL?R!==void 0?R:ue:null,continueOnError:!0,defer_duplicate_check:!1,fileOptions:we=>({docTitle:de||Qs(we.name),docType:ce.get(ns(we))||void 0}),onProgress:we=>{ae&&It({current:we.filter(We=>We.status===zt.COMPLETED||We.status===zt.FAILED).length,total:V,failedCount:we.filter(We=>We.status===zt.FAILED).length})},onFileComplete:we=>{lt.set(we.file,we),we.success&&(Ls(m,"documents"),m.invalidateQueries({queryKey:["processing-steps",c]}))}});for(const we of L){const We=lt.get(we);try{if(!(We!=null&&We.success))throw(We==null?void 0:We.error)instanceof Error?We.error:new Error((We==null?void 0:We.error)||"Upload was not acknowledged. Please try again.");ae?Fe.push({file_name:we.name,status:"success",document_id:We.documentId}):x({title:"Uploaded",description:"Processing continues in the background.",variant:"success"})}catch(cs){const _e=cs;if(Te("[CommandSurface] Caught upload error:",_e==null?void 0:_e.message,"isUpdateOrVersion:",_e==null?void 0:_e.isUpdateOrVersion,"isDuplicate:",_e==null?void 0:_e.isDuplicate,"data:",_e==null?void 0:_e.data),_e.isUpdateOrVersion&&_e.data){const ds=_e.data.storagePath;if(Te("[CommandSurface] Update/version candidate detected, storagePath:",ds),!ds)W("CommandSurface",new Error("Missing storagePath in update/version error"),_e.data);else if(ae){Fe.push({file_name:we.name,status:"skipped",error_category:"version_conflict",error_message:"A similar document was detected.",guidance:"Upload individually to choose update or new version."});continue}else{Qt({existingDoc:{id:_e.data.existing_doc_id,title:_e.data.existing_title,version_number:_e.data.existing_version_number||1},fileData:{content_hash:_e.data.content_hash,file_size:we.size,source_ref:{path:ds},extracted_text:_e.data.extracted_text||void 0}}),ee(!0),be=!0;continue}}if(_e.isDuplicate&&_e.data){const ds=_e.data.storagePath;if(Te("[CommandSurface] Duplicate detected, storagePath:",ds),!ds)W("CommandSurface",new Error("Missing storagePath in duplicate error"),_e.data);else if(ae){Fe.push({file_name:we.name,status:"skipped",error_category:"duplicate",error_message:"A document with this name already exists.",guidance:"Check your library."});continue}else{Ft({existingDoc:{id:_e.data.existing_doc_id,title:_e.data.existing_title,updated_at:new Date().toISOString()},newFileName:we.name,file:we,fileData:{storagePath:ds,extractedText:_e.data.extracted_text||void 0}}),ft(!0),be=!0;continue}}if(_e.isSizeError){ae?Fe.push({file_name:we.name,status:"failed",error_category:"size_limit",error_message:"Exceeds file size limit.",guidance:"Reduce file size or split into smaller files."}):Je(x,_e,"uploading");continue}if(!ae)throw cs;const As=(_e==null?void 0:_e.message)||String(cs)||"Unknown error",Lr=As.includes("Failed to fetch")||As.includes("NetworkError")||As.includes("Load failed")||As.includes("ERR_CONNECTION"),Fr=As.toLowerCase().includes("unsupported"),wn=!!s&&_e.statusCode===403;Fe.push({file_name:we.name,status:"failed",error_category:Lr?"network_error":Fr?"unsupported_format":"server_error",error_message:wn?"The destination folder is unavailable or you cannot add these files.":Lr?"Connection lost during upload.":Fr?"Unsupported file format.":"Processing failed.",guidance:wn?"Choose another folder in the Library and retry the upload.":Lr?"Check your connection and try again.":Fr?"Convert to PDF and re-upload.":"Try uploading this file again."}),W("useUploadPipeline",cs,`File "${we.name}" failed:`);continue}}ae&&(Lt(Fe.map((we,We)=>{var cs;return{...we,entry_id:ns(L[We]),relative_path:(cs=ms(L[We]))==null?void 0:cs.relative_path}})),es(!0)),w.current=!1,be||(Me(),a==null||a())}catch(lt){const we=nc(lt);Te("[CommandSurface] Outer catch -",we.technical),x({title:we.title,de
3scription:we.description,variant:"destructive"})}finally{w.current=!1,O(!1),It(null)}},[L,s,r,c,h==null?void 0:h.id,ts,de,A,Y,f,ue,x,Me,a,m,ce]),ki=i.useCallback(async()=>{if(!Z.trim()){x({title:"URL Required",description:"Please enter a URL first.",variant:"destructive"});return}ut(!0);try{const R=await Ji({url:Z.trim(),title:de.trim()||void 0});if(R.summary)B(R.summary),R.extractedTitle&&(!de.trim()||de==="Watch"||de.startsWith("http"))&&F(R.extractedTitle);else throw new Error("No summary returned")}catch(R){W("CommandSurface",R,"Error generating summary:"),x({title:"Summary Generation Failed",description:R instanceof Error?R.message:"Could not generate summary. Please enter one manually.",variant:"destructive"})}finally{ut(!1)}},[Z,de,x]),Ci=i.useCallback(async()=>{if(!(!Z||!ur(Z)||!c||!(h!=null&&h.id))){if(!(A!=null&&A.trim())){x({title:"Summary Required",description:"Please generate or enter a summary before importing.",variant:"destructive"});return}O(!0);try{const V={inlineText:`${A}
4
5Source: ${Z}`,orgId:c,org_type:f,docTitle:de||Hr(Z),docSummary:A,tags:Y.length>0?Y:void 0,departmentId:f===Oe.BUSINESS||f===Oe.INTERNAL?ue:null,source_kind:"url",sourceRef:{source_url:Z,kind:"url",summary:A}};await Kr(V),x({title:"URL imported",description:"Content has been added to your library.",variant:"success"}),Me(),a==null||a(),Ls(m,"documents")}catch(R){const V=R instanceof Error?R.message:"Failed to submit URL";x({title:"Error",description:V,variant:"destructive"})}finally{O(!1)}}},[Z,c,h==null?void 0:h.id,f,de,A,Y,ue,x,Me,a,m]),Ei=i.useCallback(async R=>{if(!ye.trim()){x({title:"Missing content",description:"Please write some content before publishing.",variant:"destructive"});return}const V=de.trim()||"Untitled";O(!0);try{const be=await n(V,ye,Y,!0,{department_id:(R??ue)||void 0});if((be==null?void 0:be.action_required)==="update_or_version"){Tt({existingDoc:{id:be.existing_doc_id,title:be.existing_title},newTitle:V,content:ye,tags:[...Y]}),ft(!0);return}Me()}finally{O(!1)}},[ye,de,Y,ue,n,x,Me]),Ii=i.useCallback(async()=>{var R,V;Ce?((R=Ee.current)==null||R.stopRecording(),xe(!1),Ot()):await((V=Ee.current)==null?void 0:V.startRecording())&&(xe(!0),Rs())},[Ce,Rs,Ot]),Ti=i.useCallback(R=>{pe(V=>V?`${V} ${R}`:R),y("text"),$("text"),Ot()},[Ot]),Di=i.useCallback(R=>{dt(R),pt(!0);const V=os(new Date,"MMM d, yyyy 'at' h:mm a");Ie(`${kn}, ${V}`),Ot()},[Ot]),Ri=i.useCallback(async()=>{if(!(!Xe||!c)){Be(!0);try{if(Xe.size>fl){x({title:"Recording too large. Try a shorter recording.",variant:"destructive"});return}const R=`voice-note-${Date.now()}.webm`,V=new File([Xe],R,{type:"audio/webm"});await ts([V],{docType:Xi.AUDIO,docTitle:Ze||`${kn}, ${os(new Date,"MMM d, yyyy 'at' h:mm a")}`,inlineText:Qe||void 0,departmentId:ue}),x({title:"Voice note saved"}),Me()}catch(R){W("Voice note save failed",R),x({title:"Failed to save voice note. Please try again.",variant:"destructive"})}finally{Be(!1)}}},[Xe,Qe,Ze,c,ue,ts,x,Me]),Ai=i.useCallback(()=>{bt(null),dt(null),pt(!1),Ie("")},[]),Pi=Ce&&$e>=hl,Li=i.useCallback(async()=>{if(te.trim()){wt(!0);try{const V=(await Zi({prompt:te.trim()})).content||"",ae=te.trim();let be=ae.split(/[\n.]/)[0].slice(0,60);be.length<ae.length&&(be=be.trim()),F(be),pe(rl(V)),y("text"),$("text"),he("")}catch(R){W("CommandSurface",R,"Error generating content:"),x({title:"Generation Failed",description:R instanceof Error?R.message:"Failed to generate content. Please try again.",variant:"destructive"})}finally{wt(!1)}}},[te,x]),Fi=i.useCallback(async(R="organize",V)=>{if(!ye.trim()){x({title:"No Content",description:"Please add some content before enhancing.",variant:"destructive"});return}const ae=Cn[R]||Cn.organize;At(!0),x({title:ae.loadingText,description:"AI is processing your content..."});try{const be=ye.trim(),Fe=await nl(be,R,V);if(Fe.html){const lt=al({sourceHtml:be,enhancementType:R,enhancedMarkdown:Fe.markdown,enhancedHtml:Fe.html,changeSummary:Fe.changeSummary,instruction:V});lt?xt(lt):x({title:"Nothing to change",description:"No issues found — this text is already clean.",variant:"success"})}else x({title:"Enhancement Failed",description:Fe.error||"AI returned an empty response. Please try again.",variant:"destructive"})}catch(be){W("CommandSurface",be,"Error enhancing content:"),x({title:"Enhancement Failed",description:"Failed to enhance content. Please try again.",variant:"destructive"})}finally{At(!1)}},[ye,x]),Oi=i.useCallback(()=>{gt&&(pe(gt.html),xt(null))},[gt]),$i=i.useCallback(()=>{xt(null)},[]),Pr=i.useCallback(R=>{const V=R.trim();N(""),F(""),pe(V),requestAnimationFrame(()=>{y("text"),$("text")})},[]),Mi=i.useCallback(R=>{const V=R.target.value;N(V),ur(V)?$("url"):V.length>0?($("text"),V.length>=50&&Pr(V)):$("upload")},[Pr]),Ui=i.useCallback(R=>{w.current||U(V=>{const ae=V.filter((be,Fe)=>Fe!==R);return ae.length===0?Me():ae.length===1&&F(Qs(ae[0].name)),ae})},[Me]),Bi=i.useCallback(R=>{R.preventDefault(),S(!0),$("file")},[]),zi=i.useCallback(R=>{R.preventDefault(),S(!1),E.length===0&&$("upload")},[E]),qi=i.useCallback(R=>{R.preventDefault(),S(!1),!w.current&&cc(R).then(V=>{ss(V)})},[ss]);return i.useEffect(()=>{const R=V=>{var ae;V.key==="Escape"&&Me(),(V.metaKey||V.ctrlKey)&&V.key==="k"&&(V.preventDefault(),(ae=Ds.current)==null||ae.focus())};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[Me]),{mode:v,setMode:y,iconState:l,setIconState:$,isDragOver:k,isExpanded:v!=="idle",inputValue:E,setInputValue:N,placeholderIndex:Q,isPlaceholderFading:K,handleInputChange:Mi,expandToTextMode:Pr,selectedFiles:L,setSelectedFiles:U,urlValue:Z,setUrlValue:le,isEditingUrl:De,setIsEditingUrl:fe,textContent:ye,setTextContent:pe,title:de,setTitle:F,tags:Y,setTags:ie,tagInput:oe,setTagInput:C,summary:A,setSummary:B,aiPrompt:te,setAiPrompt:he,departmentId:ue,setDepartmentId:Ae,handleFileSelect:ss,handleRemoveFile:Ui,handleFileUpload:Ni,handleUrlSubmit:Ci,handleTextPublish:Ei,handleGenerateAI:Li,handleGenerateSummary:ki,handleEnhanceContent:Fi,handleAddTag:Re,handleSuggestionToggle:$t,tagSuggestions:p,selectedDocType:qe,handleDocTypeSelect:Si,suggestedType:ls,customChipTypes:Rr,fileDocTypeMap:ce,showPreferencesSaved:ve,batchDetection:G,handleFamilyConfirm:_i,handleFamilyDismiss:ji,duplicateCandidate:ge,updateCandidate:Ke,textDuplicateInfo:et,setTextDuplicateInfo:Tt,showDuplicateDialog:Yt,setShowDuplicateDialog:ft,showVersionConfirmation:j,setShowVersionConfirmation:ee,showUploadAnywayConfirmation:me,setShowUploadAnywayConfirmation:Le,handleBlockDuplicate:Ar,handleShowVersionConfirmation:_,handleCreateVersionFromDuplicate:z,handleUploadAsNewFromVersion:H,handleEditExistingFromDuplicate:je,handleShowUploadAnywayConfirmation:st,handleUploadAnyway:Ge,setDuplicateCandidate:Ft,setUpdateCandidate:Qt,batchResults:tt,showBatchSummary:Ht,setShowBatchSummary:es,isRecording:Ce,setIsRecording:xe,recordingTime:$e,isProcessing:b,setIsProcessing:P,voiceRef:Ee,handleVoiceToggle:Ii,handleVoiceTranscript:Ti,handleVoiceNoteTranscript:Di,stopRecordingTimer:Ot,voiceReviewState:Kt?{blob:Xe,transcript:Qe,duration:$e,title:Ze}:null,isSavingVoiceNote:ot,maxDurationWarning:Pi,handleVoiceNoteSave:Ri,handleVoiceNoteDiscard:Ai,handleVoiceReviewTitleChange:Ie,setVoiceBlob:bt,isUploading:T,isGeneratingAI:Wt,isEnhancingContent:_t,enhancePreview:gt,acceptEnhancePreview:Oi,rejectEnhancePreview:$i,generatingSummary:jt,uploadProgress:Pt,uploadFileProgress:Ws,handleDragOver:Bi,handleDragLeave:zi,handleDrop:qi,orgType:f,orgId:c,inputRef:Ds,fileInputRef:Dr,navigate:g,handleReset:Me}}
5const vc=[[ps,"Separate document created","not a version"],[Ss,"No version history","documents exist independently"],[nn,"Both in search results","can cause confusion"],[Ss,"Double resources","both processed separately"]];function bc({open:t,onOpenChange:s,existingDoc:r,newFileName:n,onConfirm:a,onCancel:o}){const[d,g]=i.useState(!1),c=()=>{a(),s(!1)},u=()=>{o(),s(!1)};return e.jsxs(nt,{open:t,onOpenChange:s,tier:"form",icon:e.jsx(Et,{className:"h-5 w-5"}),iconClassName:"dialog-header-icon-error",title:"Upload as Separate Document",description:"This will create a duplicate document in your library.",footer:e.jsxs(e.Fragment,{children:[e.jsx(Ye,{variant:"secondary",onClick:u,icon:e.jsx(wl,{className:"h-4 w-4 mr-1.5"}),children:"Back"}),e.jsx(Ye,{variant:"destructive",onClick:c,icon:e.jsx(ps,{className:"h-4 w-4 mr-1.5"}),children:"Upload Anyway"})]}),children:[e.jsx(Os,{children:"Document Info"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-white/[0.04] border border-white/8",children:[e.jsx(Os,{tone:"muted",children:"Existing Document"}),e.jsx("div",{className:"text-sm text-[var(--platform-text-primary)]",children:r.title}),r.version_number&&e.jsxs("span",{className:"text-xs text-[var(--platform-text-muted)]",children:["v",r.version_number]})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-red-500/5 border border-red-500/20",children:[e.jsx(Os,{className:"text-red-400/70",children:"New File"}),e.jsx("div",{className:"text-sm text-[var(--platform-text-primary)]",children:n})]})]}),e.jsxs(eo,{variant:"danger",className:"flex items-center gap-2",children:[e.jsx(Et,{className:"h-4 w-4 flex-shrink-0 text-red-400"}),e.jsx("p",{className:"text-xs font-medium text-red-400",children:"This will create duplicate content in your knowledge base"})]}),e.jsxs(yl,{open:d,onOpenChange:g,children:[e.jsx(vl,{className:"w-full mt-3 rounded-lg px-3 py-2 text-left transition-all focus:outline-none bg-white/[0.03] border border-white/8 hover:bg-white/[0.06]",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-3.5 w-3.5 text-[var(--gold)]"}),e.jsx("span",{className:"text-xs text-[var(--platform-text-muted)]",children:"What will happen?"})]}),e.jsx(Vs,{className:`h-3.5 w-3.5 transition-transform text-[var(--platform-text-muted)] ${d?"rotate-180":""}`})]})}),e.jsx(bl,{children:e.jsx("div",{className:"mt-2 rounded-lg px-3 py-3 space-y-3 bg-white/[0.03]",children:vc.map(([h,x,m])=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(h,{className:"h-3.5 w-3.5 mt-0.5 flex-shrink-0 text-red-400"}),e.jsxs("span",{className:"text-xs text-[var(--platform-text-muted)]",children:[e.jsx("span",{className:"font-medium text-[var(--platform-text-primary)]",children:x})," ","— ",m]})]},x))})})]})]})}function $n(t){if(typeof t!="number"&&typeof t!="string"||typeof t=="string"&&!/^\d+$/.test(t))return null;const s=Number(t);return Number.isSafeInteger(s)&&s>=0?s:null}function wc(t){if(t.code==="PGRST202")return!0;const s=t.message??"";return s.includes("Could not find the function")&&s.includes("rpc_document_graph_counts")}async function _c(t,s){if(s.length===0)return{};const r={},n=new Set(s),{data:a,error:o}=await X.rpc("rpc_document_graph_counts",{p_org_id:t,p_doc_ids:s});if(o){if(wc(o))return r;throw W("fetchDocumentGraphCounts",o,"RPC failed"),new Error(o.message)}for(const d of a??[])n.has(d.doc_id)&&(r[d.doc_id]={entities:$n(d.entity_count),relationships:$n(d.relationship_count),centrality:null});return r}async function jc(t,s=100){const r=typeof s=="number"?s:s.limit??100,n=typeof s=="number"?!0:s.includeEntityCounts!==!1;if(!t)return console.warn("Cannot fetch processing jobs: orgId is null"),[];const{data:a,error:o}=await X.from("organizations").select("org_type").eq("id",t).single();if(o||!a)return console.warn("Cannot fetch processing jobs: failed to get org_type",o),[];const{data:d,error:g}=await X.from("embedding_jobs").select("job_id, status, created_at, record_id, last_error, job_type, chunks_created, chunks_failed, archived_at, archived_reason").eq("source",a.org_type).or("status.in.(pending,processing,transcript_ready),status.eq.completed,status.eq.failed").order("created_at",{ascending:!1}).limit(r),c=d||[],u=new Date(Date.now()-3600*1e3).toISOString();if(g)throw W("useProcessingJobs",g,"Error fetching embedding jobs:"),g;const h=c,x=(h==null?void 0:h.filter(b=>b.job_type==="audio_transcribe"||b.job_type==="video_process"))||[],m=(h==null?void 0:h.filter(b=>!x.includes(b)))||[],f=x.map(b=>
5b.record_id).filter(b=>b!==null);let p=[];if(f.length>0){const{data:b}=await X.from("kb_documents").select("id, title, created_at, created_by, department_id, source_ref").in("id",f);p=b||[]}const v=x.map(b=>b.job_id).filter(b=>b!==null);let y=[];if(v.length>0){const{data:b}=await X.from("transcription_staging").select("job_id, status").in("job_id",v);y=b||[]}const I=m.map(b=>b.record_id).filter(b=>b!==null);let M=[];if(I.length>0){const{data:b}=await X.from("kb_documents").select("id, title, created_at, status, processing_state, source_ref, entity_extraction_state, entity_extraction_error, is_active, created_by, department_id").in("id",I);M=b||[]}const k=M.filter(b=>b.entity_extraction_state==="complete"||b.entity_extraction_state==="skipped").map(b=>b.id),S={};if(n&&k.length>0&&t)try{Object.assign(S,await _c(t,k))}catch{}const T=M.filter(b=>b.is_active===!1&&(b.status==="completed"||b.processing_state==="completed")).map(b=>b.id),O={};if(T.length>0){const{data:b}=await X.from("document_duplicate_flags").select("flagged_doc_id, similar_doc_id, doc_id, detection_metadata").in("flagged_doc_id",T);if(b)for(const P of b){const l=P.detection_metadata,$=(l==null?void 0:l.similar_doc_title)||"Unknown document";P.flagged_doc_id&&(O[P.flagged_doc_id]={originalTitle:$})}}const w=I.filter(b=>!M.find(P=>P.id===b));if(w.length>0){const{data:b}=await X.from("document_sections").select("id, doc_id").in("id",w),P=(b==null?void 0:b.map(l=>l.doc_id))||[];if(P.length>0){const l=P.join(","),{data:$}=await X.from("kb_documents").select("id, title, created_at, source_ref").or(`source_ref->>note_id.in.(${l}),source_ref->>upload_id.in.(${l})`);$&&(M=[...M,...$])}}return(h||[]).filter(b=>b.status===rt.CANCELLED?!1:(b.status===rt.COMPLETED||b.status===rt.TRANSCRIPT_READY)&&b.job_type==="audio_transcribe"?!!(y==null?void 0:y.find(l=>l.job_id===b.job_id)):b.archived_at&&b.archived_reason==="cancelled_by_user"?!1:b.status===rt.COMPLETED&&b.archived_reason==="completed_ok"?!!(!b.archived_at||b.archived_at&&b.archived_at>u):!0).map(b=>{var L;let P;if(x.includes(b)?P=p==null?void 0:p.find(U=>U.id===b.record_id):P=M==null?void 0:M.find(U=>U.id===b.record_id),!P)if(b.status===rt.PENDING||b.status===rt.PROCESSING||b.status===rt.EMBEDDING)P={id:b.record_id||"",title:`Processing... (Job ${b.job_id.substring(0,8)})`,created_at:b.created_at};else return null;const l=new Date(b.created_at),Q=new Date().getTime()-l.getTime(),re=P&&"status"in P&&P.status==="completed";let K="uploading",D=0;if(re&&b.status!==rt.FAILED)K="completed",D=100;else if(b.status===rt.COMPLETED)if(b.job_type==="audio_transcribe"){const U=y==null?void 0:y.find(Z=>Z.job_id===b.job_id);(U==null?void 0:U.status)==="saved"||(U==null?void 0:U.status)==="processed"?(K="completed",D=100):(U==null?void 0:U.status)==="transcribed"?(K="processing",D=90):(K="completed",D=100)}else K="completed",D=100;else if(b.status===rt.TRANSCRIPT_READY)if(b.job_type==="audio_transcribe"){const U=y==null?void 0:y.find(Z=>Z.job_id===b.job_id);(U==null?void 0:U.status)==="transcribed"?(K="processing",D=90):(K="processing",D=85)}else K="processing",D=85;else b.status===rt.FAILED?(K="failed",D=0):b.status===rt.PROCESSING||b.status===rt.EMBEDDING?(K="embedding",D=75):b.status===rt.PENDING&&(Q>3e4?(K="processing",D=50):(K="uploading",D=25));let E=null;if(b.job_type==="audio_transcribe"){const U=y==null?void 0:y.find(Z=>Z.job_id===b.job_id);E=(U==null?void 0:U.status)??null}const N=P.id?S[P.id]:null;return{id:b.job_id,title:P.title,status:K,progress:D,uploadedAt:b.created_at,error:b.last_error||null,jobType:b.job_type,jobId:b.job_id,documentId:P.id,createdAt:b.created_at,transcriptionStatus:E,chunks_created:b.chunks_created,chunks_failed:b.chunks_failed,entityExtractionState:P.entity_extraction_state||null,entityExtractionError:P.entity_extraction_error||null,entitiesCount:(N==null?void 0:N.entities)??null,relationshipsCount:(N==null?void 0:N.relationships)??null,centralityCount:(N==null?void 0:N.centrality)??null,isDuplicate:P.is_active===!1&&K==="completed",duplicateOfTitle:P.id?(L=O[P.id])==null?void 0:L.originalTitle:void 0,createdBy:P.created_by??null,departmentId:P.department_id??null,source_ref:P.source_ref??null}}).filter(b=>b!==null)}const Sc=3e4,Nc="uploading",kc=new Set([Nc,rt.PROCESSING,rt.EMBEDDING]);function Cc(t){return t===void 0?!0:t.some(s=>kc.has(s.status))}function mn(t,s){const r=ct(),{user:n}=Is(),a=i.useCallback(()=>{r.invalidateQueries({queryKey:["processing-steps",t]})},[r,t]);return to(!ql()&&t?ro(t,no.processingJobs):null,{filter:o=>o.event!=="UPDATE"||so(o.payload),onSignal:a,onReconnect:a}),He({queryKey:["processing-steps",t,n==null?void 0:n.id,(s==null?void 0:s.limit)??100,(s==null?void 0:s.includeEntityCounts)!==!1],queryFn:()=>jc(t,{limit:(s==null?void 0:s.limit)??100,includeEntityCounts:(s==null?void 0:s.includeEntityCounts)!==!1}
5),enabled:!!t&&!!(n!=null&&n.id),refetchInterval:o=>Cc(o.state.data)?Sc:!1,staleTime:(s==null?void 0:s.staleTime)??2e3,gcTime:3e4,retry:(o,d)=>{var g,c;return(g=d==null?void 0:d.message)!=null&&g.includes("400")||(c=d==null?void 0:d.message)!=null&&c.includes("permission")?!1:o<3},retryDelay:o=>Math.min(1e3*2**o,3e4)})}const Ec=900*1e3,Ic=5,Tc=5e3;function Dc(t){if(!(t!=null&&t.length))return[];const s=new Date(Date.now()-Ec).toISOString();return t.filter(r=>r.uploadedAt>s).slice(0,Ic)}function Rc(t){switch(t){case"completed":return e.jsx(Ea,{className:"h-3.5 w-3.5 shrink-0",style:{color:"var(--emerald, #34d399)"}});case"failed":return e.jsx(gs,{className:"h-3.5 w-3.5 shrink-0",style:{color:"var(--coral, #f87171)"}});case"uploading":case"processing":case"embedding":default:return e.jsx(it,{className:"h-3.5 w-3.5 shrink-0 animate-spin",style:{color:"var(--gold)"}})}}function Ac({orgId:t}){const{data:s}=mn(t,{limit:10,includeEntityCounts:!1}),r=i.useMemo(()=>Dc(s),[s]),n=r.filter(m=>m.status==="processing"||m.status==="embedding"||m.status==="uploading").length,a=r.filter(m=>m.status==="failed").length,o=r.length>0&&n===0&&a===0,[d,g]=i.useState(!1);i.useEffect(()=>{if(!o){g(!1);return}const m=setTimeout(()=>g(!0),Tc);return()=>clearTimeout(m)},[o]);const u=i.useCallback(()=>r.length===0?null:o?"All complete":a>0&&n===0?`${a} Failed`:n>0?`${n} Processing`:null,[r.length,o,a,n])();if(!u||o&&d)return null;const h=a>0,x=n>0;return e.jsxs(ao,{children:[e.jsx(io,{asChild:!0,children:e.jsxs("button",{type:"button",className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full text-[12px] font-medium transition-colors animate-in fade-in duration-200",style:{backgroundColor:h?"rgba(248, 113, 113, 0.10)":"rgba(197, 160, 90, 0.10)",border:`1px solid ${h?"rgba(248, 113, 113, 0.25)":"rgba(197, 160, 90, 0.25)"}`,color:h?"var(--coral, #f87171)":"var(--gold)"},"aria-label":"View recent upload status",children:[x&&e.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full opacity-75",style:{backgroundColor:"var(--gold)"}}),e.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2",style:{backgroundColor:"var(--gold)"}})]}),o&&e.jsx(Ea,{className:"h-3.5 w-3.5 shrink-0",style:{color:"var(--emerald, #34d399)"}}),h&&!x&&e.jsx(gs,{className:"h-3.5 w-3.5 shrink-0",style:{color:"var(--coral, #f87171)"}}),e.jsx("span",{children:u})]})}),e.jsx(oo,{tier:"info",className:"p-0 rounded-xl overflow-hidden",align:"end",side:"bottom",avoidCollisions:!1,children:e.jsxs("div",{className:"p-3",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider mb-2",style:{color:"var(--gold)"},children:"Recent Uploads"}),e.jsx("div",{className:"flex flex-col gap-1",children:r.map(m=>e.jsxs("div",{className:"flex items-center gap-2.5 px-2.5 py-2 rounded-lg",children:[Rc(m.status),e.jsx("span",{className:"text-[12px] text-[var(--platform-text-primary)] truncate flex-1",children:m.title}),e.jsx("span",{className:"text-[10px] shrink-0",style:{color:"var(--platform-text-muted)"},children:vr(m.uploadedAt,{addSuffix:!0})})]},m.id))}),e.jsx("div",{className:"mt-2 pt-2 border-t border-[rgba(255,255,255,0.06)]",children:e.jsxs(zs,{to:ha.ACTIVITY,className:"flex items-center justify-between px-2.5 py-1.5 rounded-lg text-[12px] font-medium transition-colors hover:bg-white/[0.04]",style:{color:"var(--gold)"},children:[e.jsx("span",{children:"View all uploads"}),e.jsx(Ia,{className:"h-3.5 w-3.5"})]})})]})})]})}function Pc({open:t,on_close:s,results:r}){const n=Cs(),a=r.filter(h=>h.status==="success"),o=r.filter(h=>h.status==="failed"),d=r.filter(h=>h.status==="skipped"),g=r.length,c=o.length===0&&d.length===0,u=c?"Upload Complete":`Upload Complete: ${a.length} of ${g} succeeded`;return e.jsx(nt,{open:t,onOpenChange:h=>{h||s()},tier:"detail",title:u,icon:c?e.jsx(js,{className:"h-5 w-5"}):e.jsx(Et,{className:"h-5 w-5"}),iconClassName:c?"dialog-header-icon-success":void 0,description:"Review your uploaded, skipped and failed files.",footer:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[a.length>0&&e.jsx(q,{variant:"secondary",onClick:()=>{s(),n(ha.ACTIVITY)},children:"View processing"}),e.jsx(q,{variant:"primary",onClick:()=>{s(),n(qt.LIBRARY)},children:"View Library"})]}),children:e.jsxs("div",{className:"flex flex-col gap-4",children:[a.length>0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Files are uploaded. Processing continues in the background."}),a.length>0&&e.jsx("div",{children:a.length<=3?e.jsx("ul",{className:"flex flex-col gap-1.5",children:a.map(h=>e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"h-4 w-4 shrink-0",style:{color:"var(--color-success)"}}),e.jsx("span",{className:"text-sm truncate",style:{color:"var(--platform-text-primary)"},children:h.relative_path||h.file_name})]},h.entry_id||h.file_name))}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(js,{className:"h-4 w-4 shrink-0",style:{color:"var(--color-success)"}}),e.jsxs("span",{className:"text-sm",style:{color:"var(--platform-text-primary)"},children:[a.length," files uploaded successfully"]})]})}),o.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Os,{children:"Failed"}),e.jsx("ul",{className:"flex flex-col gap-2",children:o.map(h=>e.jsxs("li",{className:"flex items-start gap-2 rounded-lg px-3 py-2",style:{backgroundColor:"color-mix(in srgb, var(--color-error) 8%, transparent)"},children:[e.jsx(Ss,{className:"h-4 w-4 mt-0.5 shrink-0",style:{color:"var(--color-error)"}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",style:{color:"var(--platform-text-primary)"},children:h.relative_path||h.file_name}),h.error_message&&e.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--platform-text-secondary)"},children:h.error_message}),h.guidance&&e.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--platform-text-muted)"},children:h.guidance})]})]},h.entry_id||h.file_name))})]}),d.length>0&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(Os,{children:"Skipped"}),e.jsx("ul",{className:"flex flex-col gap-2",children:d.map(h=>e.jsxs("li",{className:"flex items-start gap-2 rounded-lg px-3 py-2",style:{backgroundColor:"color-mix(in srgb, var(--platform-text-primary) 4%, transparent)"},children:[e.jsx(Et,{className:"h-4 w-4 mt-0.5 shrink-0",style:{color:"var(--color-warning)"}}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",style:{color:"var(--platform-text-primary)"},children:h.relative_path||h.file_name}),h.error_message&&e.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--platform-text-secondary)"},children:h.error_message})]})]},h.entry_id||h.file_name))})]})]})})}function Lc(){return e.jsx(Ta,{size:16,"aria-hidden":!0})}const Fc=[{id:"file",label:"Upload",icon:Da},{id:"write",label:"Create",icon:ps}];function Wa({showSyncMethod:t=!1,showManualMethods:s=!0,onManualTabChange:r,className:n}){const[a,o]=Es(),d=a.get("tab")||"file",g=t&&d===Rt,c=g?"file":sn(d)??"file",u=h=>{o(x=>{const m=new URLSearchParams(x);return m.set("tab",h),m.delete("mode"),m},{replace:!0}),h!==Rt&&(r==null||r(h))};return e.jsxs("div",{className:n??"flex flex-wrap items-center gap-1",role:"tablist","aria-label":"How do you want to get knowledge in?",children:[(s?Fc:[]).map(({id:h,label:x,icon:m})=>e.jsxs(q,{variant:"tab",role:"tab","aria-selected":!g&&c===h,"data-active":!g&&c===h,onClick:()=>u(h),children:[e.jsx(m,{size:16}),e.jsx("span",{children:x})]},h)),t&&e.jsxs(q,{variant:"tab",role:"tab","aria-selected":g,"data-active":g,onClick:()=>u(Rt),children:[e.jsx(Lc,{}),e.jsx("span",{children:"Sync from an app"})]})]})}const Oc="/library?department=pending-review";function $c({syncedCount:t,skippedCount:s,errorCount:r,total:n,awaitingReviewCount:a}){const o=a>0?` • ${a} awaiting review`:"";return r>0?{title:"Sync completed with errors",description:`Synced ${t} • Skipped ${s} • Errors ${r}${o}`,variant:"warning"}:{title:"Sync complete",description:`${t>0?`Synced ${t} document${t!==1?"s":""}${s>0?` • Skipped ${s}`:""}`:`All ${n} documents were already synced`}${o}`,variant:"success"}}function Mc(){const t=Cs();return e.jsx(pa,{altText:"Review documents awaiting an access group",onClick:()=>t(Oc),children:"Review"})}const Uc=t=>["team-connections",t];function Bc(t){const{role:s}=Ve(),r=Gs(s);return He({queryKey:Uc(t),enabled:!!t&&r,queryFn:async()=>
5{if(!t)throw new Error("orgId required");const{data:{session:n},error:a}=await X.auth.getSession();if(a)throw W("useTeamConnections",a,"Session error:"),new Error("Authentication failed: "+a.message);if(!n)throw new Error("No active session found. Please sign in again.");return(await uo(t)).connections}})}function zc(t){const{toast:s}=ze();return qs({invalidates:["teamConnections","connectionAuditLog"],settlement:"immediate",mutationFn:async r=>{const{data:{session:n},error:a}=await X.auth.getSession();if(a)throw W("useDisableTeamConnection",a,"Session error:"),new Error("Authentication failed: "+a.message);if(!n)throw new Error("No active session found. Please sign in again.");return lo(r)},onError:r=>{Je(s,r,"disabling that connection")}})}function qc(t){const{toast:s}=ze();return qs({invalidates:["teamConnections","connectionAuditLog"],settlement:"immediate",mutationFn:async r=>{const{data:{session:n},error:a}=await X.auth.getSession();if(a)throw W("useEnableTeamConnection",a,"Session error:"),new Error("Authentication failed: "+a.message);if(!n)throw new Error("No active session found. Please sign in again.");return co(r)},onError:r=>{Je(s,r,"re-enabling that connection")}})}const Gc=(t,s)=>["connection-audit-log",t,s];function Vc(t,s={}){const{connectionId:r,limit:n=50,enabled:a=!0}=s,{role:o}=Ve(),d=Gs(o);return He({queryKey:Gc(t,r),enabled:!!t&&d&&a,queryFn:async()=>{if(!t)throw new Error("orgId required");const{data:{session:g},error:c}=await X.auth.getSession();if(c)throw W("useConnectionAuditLog",c,"Session error:"),new Error("Authentication failed: "+c.message);if(!g)throw new Error("No active session found. Please sign in again.");return(await mo(t,{connection_id:r,limit:n})).entries}})}const Kc={google:"Google Drive",trello:"Trello",notion:"Notion",slack:"Slack",dropbox:"Dropbox",hubspot:"HubSpot"};function Wc(t){switch(t){case"created":case"enabled":return"success";case"reauth_required_detected":case"alert_sent":return"warning";case"disabled":case"token_refresh_failed":return"error";case"member_removed":case"member_deleted":return"info";default:return"neutral"}}function Yc({orgId:t,connection:s,open:r,onOpenChange:n}){const a=Kc[s.provider]??s.provider,{data:o,isLoading:d,error:g}=Vc(t,{connectionId:s.id,limit:50,enabled:r});return e.jsx(nt,{open:r,onOpenChange:n,title:"Connection history",description:`Audit log for ${s.user_full_name}'s ${a} connection.`,tier:"detail",children:e.jsxs("div",{className:"flex flex-col gap-2 min-h-[200px]",children:[d&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(it,{className:"h-5 w-5 animate-spin",style:{color:"var(--platform-text-muted)"}})}),g&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg bg-destructive/10 border border-destructive/20",role:"alert",children:[e.jsx(gs,{className:"h-4 w-4 shrink-0 mt-0.5 text-destructive"}),e.jsx("p",{className:"text-sm text-destructive",children:"Couldn't load the audit history. Try again in a moment."})]}),!d&&!g&&o&&o.length===0&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-muted)"},children:"No history yet."})}),!d&&o&&o.length>0&&o.map(c=>e.jsxs("div",{className:"flex items-start justify-between gap-3 p-3 rounded-lg",style:{backgroundColor:"var(--white-3)",border:"1px solid var(--white-6)"},children:[e.jsxs("div",{className:"flex flex-col gap-1 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(yt,{variant:Wc(c.action),size:"sm",children:fo[c.action]??c.action}),e.jsxs("span",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:["by"," ",c.actor_email??e.jsx("span",{className:"italic",children:"system"})]})]}),c.reason&&e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-secondary)"},children:c.reason})]}),e.jsx("span",{className:"text-xs shrink-0",style:{color:"var(--platform-text-muted)"},title:c.created_at,children:vr(c.created_at)})]},c.id))]})})}const Hc={google:"Google Drive",trello:"Trello",notion:"Notion",slack:"Slack",dropbox:"Dropbox",hubspot:"HubSpot"};function Qc(t){switch(t){case vt.ACTIVE:return"success";case vt.REAUTH_REQUIRED:return"warning";case vt.ERROR:return"error";
5case vt.DISABLED:default:return"neutral"}}function Mn(t,s){return s?"Disabled":t===vt.REAUTH_REQUIRED?"Reconnect needed":t===vt.ERROR?"Sync error":"Active"}function Jc({orgId:t,connection:s}){var p,v,y;const[r,n]=i.useState(!1),[a,o]=i.useState(!1),[d,g]=i.useState(""),c=zc(),u=qc(),h=!!s.disabled_at,x=Hc[s.provider]??s.provider,m=((y=(v=(p=s.sync_config)==null?void 0:p.google)==null?void 0:v.folders)==null?void 0:y.length)??0,f=()=>{c.mutate({connection_id:s.id,reason:d.trim()||void 0},{onSuccess:()=>{o(!1),g("")}})};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:Ue("flex items-center justify-between gap-4 p-4 rounded-xl","border border-[rgba(255,255,255,0.08)] bg-[rgba(255,255,255,0.02)]",h&&"opacity-60"),children:[e.jsxs("div",{className:"flex items-center gap-4 min-w-0 flex-1",children:[e.jsx("div",{className:"flex items-center justify-center w-10 h-10 rounded-xl shrink-0",style:{backgroundColor:"rgba(197, 160, 90, 0.15)",border:"1px solid rgba(197, 160, 90, 0.30)"},"aria-hidden":"true",children:e.jsx(Ra,{className:"h-5 w-5",style:{color:"var(--gold)"}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium truncate",style:{color:"var(--platform-text-primary)"},children:s.user_full_name}),e.jsx(yt,{variant:"neutral",size:"sm",children:x}),e.jsx(yt,{variant:Qc(s.sync_status),size:"sm","aria-label":`Status: ${Mn(s.sync_status,s.disabled_at)}`,children:Mn(s.sync_status,s.disabled_at)})]}),e.jsxs("p",{className:"text-xs mt-1",style:{color:"var(--platform-text-secondary)"},children:[m>0?`${m} folder${m===1?"":"s"} • `:"",s.total_documents_synced," doc",s.total_documents_synced===1?"":"s"," •"," ",s.last_sync_at?`synced ${vr(s.last_sync_at)}`:"never synced"]}),h&&s.disabled_reason&&e.jsxs("p",{className:"text-xs mt-1 italic",style:{color:"var(--platform-text-muted)"},children:["Reason: ",s.disabled_reason]})]})]}),e.jsxs(ir,{children:[e.jsx(or,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon","aria-label":`Actions for ${s.user_full_name}'s ${x} connection`,children:e.jsx(mr,{className:"h-4 w-4"})})}),e.jsxs(lr,{align:"end",children:[e.jsxs(Mt,{onClick:()=>n(!0),"aria-label":`View history for ${s.user_full_name}'s ${x} connection`,children:[e.jsx(_l,{className:"h-4 w-4 mr-2"})," View history"]}),e.jsx(ga,{}),h?e.jsxs(Mt,{onClick:()=>u.mutate({connection_id:s.id}),disabled:u.isPending,"aria-label":`Re-enable ${s.user_full_name}'s ${x} connection`,children:[e.jsx(Aa,{className:"h-4 w-4 mr-2"})," Re-enable"]}):e.jsxs(Mt,{onClick:()=>o(!0),"aria-label":`Disable ${s.user_full_name}'s ${x} connection`,children:[e.jsx(jl,{className:"h-4 w-4 mr-2"})," Disable"]})]})]})]}),e.jsx(Ba,{open:a,onOpenChange:o,title:"Disable connection",description:`This pauses sync for ${s.user_full_name}'s ${x} connection. Tokens are preserved — you can re-enable any time.`,confirmLabel:"Disable",isPending:c.isPending,onConfirm:f,body:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{htmlFor:`disable-reason-${s.id}`,className:"text-xs uppercase tracking-wider",style:{color:"var(--platform-text-muted)"},children:"Reason (optional)"}),e.jsx("textarea",{id:`disable-reason-${s.id}`,className:"dialog-input min-h-[80px] resize-none",placeholder:"e.g. wrong folder, no longer needed",value:d,onChange:I=>g(I.target.value),maxLength:500,"aria-label":"Reason for disabling this connection"})]})}),e.jsx(Yc,{orgId:t,connection:s,open:r,onOpenChange:n})]})}function Xc(){const{orgId:t}=Ve(),{data:s,isLoading:r,error:n}=Bc(t);return t?e.jsxs("section",{"aria-labelledby":"team-integrations-heading",children:[e.jsxs("div",{className:Ut.sectionHeader,children:[e.jsx("h2",{id:"team-integrations-heading",className:Ut.sectionTitle,children:"Team Integrations"}),e.jsx("p",{className:Ut.sectionDescription,children:"Every active connection in your org. Disable any that shouldn't be syncing."})]}),e.jsxs("div",{className:Ue(Ut.card,"flex flex-col gap-2 p-4"),children:[r&&e.jsxs("div",{className:"flex items-center justify-center py-8 gap-2",children:[e.jsx(it,{className:"h-5 w-5 animate-spin",style:{color:"var(--platform-text-muted)"},"aria-hidden":"true"}),e.jsx("span",{className:"text-sm",style:{color:"var(--platform-text-muted)"},children:"Loading team connections…"})]}),n&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-lg",style:{backgroundColor:"rgba(248, 113, 113, 0.08)",border:"1px solid rgba(248, 113, 113, 0.20)"},role:"alert",children:[e.jsx(gs,{className:"h-4 w-4 shrink-0 mt-0.5",style:{color:"#f87171"},"aria-hidden":"true"}),e.jsx("p",{className:"text-sm",style:{color:"#f87171"},children:"Couldn't load team connections. Refresh to try again."})]}),!r&&!n&&s&&s.length===0&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-2 text-center",children:[e.jsx("div",{className:"flex items-center justify-center w-10 h-10 rounded-xl",style:{backgroundColor:"rgba(197, 160, 90, 0.10)",border:"1px solid rgba(197, 160, 90, 0.20)"},"aria-hidden":"true",children:e.jsx(an,{className:"h-5 w-5",style:{color:"var(--gold)"}})}),e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-primary)"},children:"No team connections yet."}),e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:"Encourage your managers to connect their own Drives."})]}),!r&&!n&&s&&s.length>0&&s.map(a=>e.jsx(Jc,{orgId:t,connection:a},a.id))]})]}):null}function Zc(t){const{toast:s}=ze();i.useEffect(()=>{t&&(async()=>{try{const{data:{user:r}}=await X.auth.getUser();if(!r)return;const{data:n,error:a}=await X.from("user_connections").select("id, pending_notifications").eq("user_id",r.id);if(a||!n)return;for(const o of n){const d=o.pending_notifications;if(!Array.isArray(d)||d.length===0)continue;for(const c of d){const u=c;u.pattern&&s({title:`New document family detected: ${u.pattern}`,description:`${u.file_count??0} files tracked as transactional automatically during last sync.`})}const{error:g}=await X.from("user_connections").update({pending_notifications:[]}
5).eq("id",o.id);g&&W("usePendingConnectionNotifications",g,"Failed to clear pending notifications:")}}catch(r){W("usePendingConnectionNotifications",r,"Error checking pending notifications:")}})()},[t])}const hs=3e4,kr="sync-staging";function en(t){return He({queryKey:[kr,t],queryFn:async()=>{var g;if(!t)return null;if(!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(t))return console.warn("[useSyncStaging] Invalid batch ID format:",t),null;const{data:r,error:n}=await X.from("sync_staging").select("status").eq("sync_batch_id",t);if(n)throw W("useSyncStaging",n,"Count query error:"),n;if(!r||r.length===0)return null;const{data:a,error:o}=await X.from("sync_staging").select("file_name").eq("sync_batch_id",t).eq("status",Se.PROCESSING).limit(1);return o&&W("useSyncStaging",o,"Processing query error:"),{batchId:t,total:r.length,pending:r.filter(c=>c.status===Se.PENDING).length,processing:r.filter(c=>c.status===Se.PROCESSING).length,completed:r.filter(c=>c.status===Se.COMPLETED).length,failed:r.filter(c=>c.status===Se.FAILED).length,skipped:r.filter(c=>c.status===Se.SKIPPED).length,currentFileName:(g=a==null?void 0:a[0])==null?void 0:g.file_name}},enabled:!!t,refetchInterval:s=>{const r=s.state.data;return r?r.pending>0||r.processing>0?hs:!1:hs},staleTime:1e3})}function Ya(){const t=xa();return He({queryKey:["active-sync-batches",t],queryFn:async()=>{const s=await $a();if(!s)return[];const{data:r,error:n}=await X.from("user_connections").select("id, provider").eq("user_id",s);if(n||!r||r.length===0)return[];const a=r.map(u=>u.id),o=new Map(r.map(u=>[u.id,u.provider])),{data:d,error:g}=await X.rpc("get_active_sync_batch_stats",{p_connection_ids:a});if(g)throw W("useActiveSyncBatches",g,"RPC error:"),g;return!d||d.length===0?[]:d.filter(u=>u.has_active).map(u=>({batchId:u.batch_id,provider:o.get(u.connection_id)??"google",total:u.total,pending:u.pending,processing:u.processing,completed:u.completed,failed:u.failed,skipped:u.skipped,currentFileName:u.current_file_name??void 0,startedAt:u.started_at}))},refetchInterval:s=>{const r=s.state.data;return r?r.length>0?hs:!1:hs},staleTime:1e3})}function Cr(t){if(t===null||typeof t!="object"||Array.isArray(t))return null;const s={};for(const[r,n]of Object.entries(t))n!==void 0&&(s[r]=n);return s}const Ha=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i;function Qa(t){return He({queryKey:[kr,"issues",t],queryFn:async()=>{if(!t||!Ha.test(t))return[];const{data:s,error:r}=await X.from("sync_staging").select("id, external_id, file_name, status, error_message, retry_count, metadata, processed_at").eq("sync_batch_id",t).in("status",[Se.FAILED,Se.SKIPPED]).order("processed_at",{ascending:!1,nullsFirst:!1});if(r)throw W("useSyncBatchIssues",r,"Issue query error:"),r;return(s??[]).map(a=>({id:a.id,external_id:a.external_id,file_name:a.file_name,status:a.status,error_message:a.error_message,retry_count:a.retry_count??0,metadata:Cr(a.metadata),processed_at:a.processed_at})).filter(a=>{var o;return!((o=a.metadata)!=null&&o[Bt.DISMISSED_AT])})},enabled:!!t,refetchInterval:hs,staleTime:2e3})}const ed=7,Ja=10,td=1e3,sd=5e3;function rd(t,s,r=Ja){const n=new Map;for(const o of t){let d=n.get(o.sync_batch_id);d||(d={sync_batch_id:o.sync_batch_id,connection_id:o.connection_id,provider:s.get(o.connection_id)??"google",started_at:o.created_at,finished_at:null,completed:0,failed:0,dismissed:0,skipped:0,skipped_up_to_date:0,skipped_needs_decision:0,pending:0,processing:0,total:0,is_active:!1,current_file_name:null},n.set(o.sync_batch_id,d)),d.total+=1,o.status===Se.COMPLETED?d.completed+=1:o.status===Se.FAILED?o.dismissed_at?d.dismissed+=1:d.failed+=1:o.status===Se.SKIPPED?(d.skipped+=1,o.skip_reason===ht.UP_TO_DATE?d.skipped_up_to_date+=1:o.skip_reason===ht.TITLE_COLLISION&&!o.resolved_at&&!o.dismissed_at&&(d.skipped_needs_decision+=1)):o.status===Se.PENDING?d.pending+=1:o.status===Se.PROCESSING&&(d.processing+=1,d.current_file_name??(d.current_file_name=o.file_name)),o.created_at&&(!d.started_at||o.created_at<d.started_at)&&(d.started_at=o.created_at);const g=o.processed_at??o.updated_at;g&&(!d.finished_at||g>d.finished_at)&&(d.finished_at=g)}const a=Array.from(n.values());for(const o of a)o.is_active=o.pending>0||o.processing>0,o.is_active&&(o.finished_at=null);return a.sort((o,d)=>(d.started_at??"").localeCompare(o.started_at??"")).slice(0,r)}function Xa(){const t=xa();return He({queryKey:[kr,"recent-batches",t],queryFn:async()=>{const s=await $a();if(!s)return[];const{data:r,error:n}=await X.from("user_connections").select("id, provider").eq("user_id",s);if(n)throw W("useRecentSyncBatches",n,"Connections error:"),n;if(!r||r.length===0)return[];const a=r.map(f=>f.id),o=new Map(r.map(f=>[f.id,f.provider])),d=new Date(Date.now()-ed*24*60*60*1e3).toISOString(),{data:g,error:c}=await X.from("sync_staging").select("sync_batch_id, created_at").in("connection_id",a).gte("created_at",d).order("created_at",{ascending:!1}).limit(td);if(c)throw W("useRecentSyncBatches",c,"Discovery error:"),c;const u=[],h=new Set;for(const f of g??[])if(!h.has(f.sync_batch_id)&&(h.add(f.sync_batch_id),u.push(f.sync_batch_id),u.length>=Ja))break;if(u.length===0)return[];const{data:x,error:m}=await X.from("sync_staging").select("sync_batch_id, connection_id, status, file_name, created_at, updated_at, processed_at, dismissed_at:metadata->>dismissed_at, skip_reason:metadata->>skip_reason, resolved_at:metadata->>resolved_at").in("sync_batch_id",u).order("created_at",{ascending:!1}).limit(sd);if(m)throw W("useRecentSyncBatches",m,"Detail error:"),m;return rd(x??[],o)},refetchInterval:s=>{const r=s.state.data;return r?r.some(n=>n.is_active)?hs:!1:hs},staleTime:2e3})}
5function nd(t,s=new Date){const n={...Cr(t??null)??{}};return delete n[Bt.TERMINAL],delete n[Bt.FAILURE_REASON],delete n[Bt.ATTEMPTS],n[Bt.USER_RETRY_AT]=s.toISOString(),n}function fn(){return qs({invalidates:["syncStaging","connections"],settlement:"immediate",mutationFn:async t=>{const s=typeof t=="string"?[t]:Array.from(t);if(s.length===0)return 0;const{data:r,error:n}=await X.from("sync_staging").select("id, metadata").in("id",s);if(n)throw W("useRetrySyncItems",n,"Read-before-reset error:"),n;if(!r||r.length===0)return 0;const a=new Date,o=new Map;for(const c of r){const u=JSON.stringify(nd(c.metadata,a)),h=o.get(u);h?h.push(c.id):o.set(u,[c.id])}const d=a.toISOString();return(await Promise.all(Array.from(o.entries()).map(async([c,u])=>{const{error:h}=await X.from("sync_staging").update({status:Se.PENDING,error_message:null,processed_at:null,retry_count:0,metadata:JSON.parse(c),updated_at:d}).in("id",u);if(h)throw W("useRetrySyncItems",h,"Reset update error:"),h;return u.length}))).reduce((c,u)=>c+u,0)}})}function ad(t,s=new Date){return{...Cr(t??null)??{},[Bt.DISMISSED_AT]:s.toISOString()}}function id(){return qs({invalidates:["syncStaging","connections"],settlement:"immediate",mutationFn:async t=>ho(t)})}function od(t){const s=Cr(t);if(!s)return null;const r={};for(const[n,a]of Object.entries(s))r[n]=a;return r}function ld(t){return He({queryKey:[kr,"latest-by-file",t],queryFn:async()=>{if(!t||!Ha.test(t))return[];const{data:s,error:r}=await X.from("sync_staging").select("id, external_id, sync_batch_id, doc_id, file_name, status, error_message, metadata, web_view_link, processed_at, created_at, mime_type").eq("connection_id",t).order("created_at",{ascending:!1}).limit(cd);if(r)throw W("useLatestStagingByFile",r,"Latest staging error:"),r;const n=new Map;for(const a of s??[])n.has(a.external_id)||n.set(a.external_id,{id:a.id,external_id:a.external_id,sync_batch_id:a.sync_batch_id,doc_id:a.doc_id,file_name:a.file_name,status:a.status,error_message:a.error_message,metadata:od(a.metadata),web_view_link:a.web_view_link,mime_type:a.mime_type,processed_at:a.processed_at,created_at:a.created_at});return Array.from(n.values())},enabled:!!t,staleTime:15e3})}const cd=5e3;function Za(){return qs({invalidates:["syncStaging","connections"],settlement:"immediate",mutationFn:async t=>{const s=typeof t=="string"?[t]:Array.from(t);if(s.length===0)return 0;const{data:r,error:n}=await X.from("sync_staging").select("id, metadata").in("id",s);if(n)throw W("useDismissSyncItems",n,"Read-before-clear error:"),n;if(!r||r.length===0)return 0;const a=new Date,o=new Map;for(const c of r){const u=JSON.stringify(ad(c.metadata,a)),h=o.get(u);h?h.push(c.id):o.set(u,[c.id])}const d=a.toISOString();return(await Promise.all(Array.from(o.entries()).map(async([c,u])=>{const{error:h}=await X.from("sync_staging").update({metadata:JSON.parse(c),updated_at:d}).in("id",u);if(h)throw W("useDismissSyncItems",h,"Clear update error:"),h;return u.length}))).reduce((c,u)=>c+u,0)}})}const ei=1800*1e3;function Zs(t,s=Date.now()){const r=new Date(t).getTime();return Number.isNaN(r)?!1:s-r<ei}const dd=new Set(["trello","notion","dropbox","hubspot"]);function ud({activeSyncBatches:t,isRunSyncPending:s}){const[r,n]=i.useState(null),[a,o]=i.useState(null),[d,g]=i.useState(null),[c,u]=i.useState(null),[h,x]=i.useState(null),[m,f]=i.useState(null);return i.useEffect(()=>{if(h||s)return;const p=t.find(y=>y.provider==="google"&&Zs(y.startedAt));p&&(Te("[Integrations] Restoring active sync batch:",p.batchId),x(p.batchId),o({current:p.completed+p.skipped+p.failed,total:p.total,fileName:p.currentFileName}),g(new Date(p.startedAt).getTime()));const v=t.find(y=>dd.has(y.provider)&&Zs(y.startedAt));v&&(Te("[Integrations] Restoring active integration batch:",v.batchId),f(v.batchId),n(v.provider),u(new Date(v.startedAt).getTime()))},[t,h,s]),i.useEffect(()=>{if(!s){if(h){const p=t.find(y=>y.batchId===h);(p?!Zs(p.startedAt):d!==null&&Date.now()-d>=ei)&&(Te("[Integrations] Releasing stale Google sync batch"),x(null),o(null),g(null))}if(m){const p=t.find(v=>v.batchId===m);p&&!Zs(p.startedAt)&&(Te("[Integrations] Releasing stale integration sync batch"),f(null),n(null),u(null))}}},[t,h,m,s,d]),{currentBatchId:h,setCurrentBatchId:x,syncProgress:a,setSyncProgress:o,syncStartTime:d,setSyncStartTime:g,integrationBatchId:m,setIntegrationBatchId:f,syncingIntegration:r,setSyncingIntegration:n,integrationSyncStartTime:c,setIntegrationSyncStartTime:u}}const md=.1,fd=3;function ti(t){const s=Math.max(0,Math.floor(t/1e3)),r=Math.floor(s/60),n=s%60;return r>0?`${r}m ${n}s`:`${n}s`}function hd(t,s=Date.now()){return ti(s-t)}
5function pd(t,s,r,n=Date.now()){if(s<=0||t<=0||t>=s||t<fd||t/s<md)return null;const a=n-r;if(a<1e3)return null;const o=t/a;if(o<=0)return null;const d=(s-t)/o;return!Number.isFinite(d)||d>1440*60*1e3?null:ti(d)}function Un(t,s,r){if(t)return s?{processed:s.completed+s.skipped+s.failed,total:s.total,currentFileName:s.currentFileName}:r?{processed:r.current,total:r.total,currentFileName:r.fileName}:{processed:0,total:0}}function gd(t){return{googleSyncProgress:Un(t.isGoogleSyncing,t.googleStaging,t.googleFallback),integrationSyncProgress:Un(t.isIntegrationSyncing,t.integrationStaging),googleSyncStartTime:t.isGoogleSyncing?t.googleSyncStartTime:null,integrationSyncStartTime:t.isIntegrationSyncing?t.integrationSyncStartTime:null}}function xd(t){return t?{title:"Still loading your connections",description:"Try again in a moment."}:{title:"Google Drive is not connected yet",description:"Connect Google Drive first, then choose what syncs.",variant:"warning"}}function Bn(t){const s=t==="trello"?"boards":"folders",r=t==="trello"?"Trello":"Dropbox";return{title:`Select ${s} first`,description:`Choose which ${r} ${s} to sync in the Scope tab, then run Sync Now.`,variant:"warning"}}const yd="_wrapper_1nghc_1",vd="_track_1nghc_5",bd="_fill_1nghc_19",wd="_timing_1nghc_44",_d="_stats_1nghc_48",jd="_fileName_1nghc_60",Sd="_failedCount_1nghc_68",rs={wrapper:yd,track:vd,fill:bd,timing:wd,stats:_d,fileName:jd,failedCount:Sd};function si({processed:t,total:s,failed:r=0,currentFileName:n,startedAt:a=null,variant:o="full"}){const[d,g]=i.useState(()=>Date.now());i.useEffect(()=>{if(!a)return;g(Date.now());const p=setInterval(()=>g(Date.now()),1e3);return()=>clearInterval(p)},[a]);const c=s>0;if(!c&&!a)return null;const u=c?Math.round(t/s*100):0,h=c&&r>0&&r/s>.5,x=`file${s!==1?"s":""}`,m=a!=null?hd(a,d):null,f=a!=null&&c?pd(t,s,a,d):null;return e.jsxs("div",{className:rs.wrapper,"data-variant":o,children:[e.jsx("div",{className:rs.track,role:"progressbar","aria-valuenow":c?u:void 0,"aria-valuemin":0,"aria-valuemax":100,"aria-label":c?`Sync progress: ${t} of ${s} ${x}`:"Sync in progress","data-indeterminate":c?void 0:"",children:e.jsx("div",{className:rs.fill,"data-error":h?"":void 0,"data-indeterminate":c?void 0:"",style:c?{width:`${u}%`}:void 0})}),e.jsxs("div",{className:rs.stats,children:[e.jsxs("span",{"aria-live":"polite","aria-atomic":"true",children:[c?`${t} of ${s} ${x}`:"Syncing…",m&&e.jsxs("span",{className:rs.timing,children:[" · ",m," elapsed"]}),f&&e.jsxs("span",{className:rs.timing,children:[" · ","~",f," left"]})]}),n&&e.jsx("span",{className:rs.fileName,title:n,children:n.length>30?n.slice(0,30)+"...":n}),o==="full"&&r>0&&e.jsxs("span",{className:rs.failedCount,children:[e.jsx(Ss,{className:"h-3 w-3"}),r," failed"]})]})]})}const Nd="_syncsTableContainer_9y49p_12",kd="_syncsTableHeader_9y49p_28",Cd="_syncsTableHeaderLeft_9y49p_37",Ed="_syncsTableHeaderRight_9y49p_43",Id="_syncsHeaderLabel_9y49p_49",Td="_syncsHeaderLabelText_9y49p_55",Dd="_syncsSummaryText_9y49p_63",Rd="_syncsCollapseBtn_9y49p_68",Ad="_syncsTableBody_9y49p_91",Pd="_syncsEmptyState_9y49p_99",Ld="_syncsList_9y49p_125",Fd="_syncCard_9y49p_135",Od="_syncCardError_9y49p_151",$d="_syncCardProcessing_9y49p_159",Md="_syncCardLeft_9y49p_164",Ud="_syncStatusIcon_9y49p_171",Bd="_syncProviderIcon_9y49p_186",zd="_syncCardContent_9y49p_198",qd="_syncCardTitle_9y49p_206",Gd="_syncCardMeta_9y49p_215",Vd="_syncCardProgress_9y49p_223",Kd="_syncCardDate_9y49p_228",Wd="_syncStatCompleted_9y49p_233",Yd="_syncStatSkipped_9y49p_242",Hd="_syncStatFailed_9y49p_251",Qd="_syncCardActions_9y49p_267",Jd="_syncActionBtn_9y49p_438",Xd="_syncActionRetry_9y49p_463",Zd="_syncActionBtnIcon_9y49p_496",Ne={syncsTableContainer:Nd,syncsTableHeader:kd,syncsTableHeaderLeft:Cd,syncsTableHeaderRight:Ed,syncsHeaderLabel:Id,syncsHeaderLabelText:Td,syncsSummaryText:Dd,syncsCollapseBtn:Rd,syncsTableBody:Ad,syncsEmptyState:Pd,syncsList:Ld,syncCard:Fd,syncCardError:Od,syncCardProcessing:$d,syncCardLeft:Md,syncStatusIcon:Ud,syncProviderIcon:Bd,syncCardContent:zd,syncCardTitle:qd,syncCardMeta:Gd,syncCardProgress:Vd,syncCardDate:Kd,syncStatCompleted:Wd,syncStatSkipped:Yd,syncStatFailed:Hd,syncCardActions:Qd,syncActionBtn:Jd,syncActionRetry:Xd,syncActionBtnIcon:Zd},eu={google:"google-drive",trello:"trello",notion:"notion",slack:"slack",dropbox:"dropbox",webhook:"webhook",hub
5spot:"hubspot"};function tu({sync:t,onRetry:s,onDelete:r,runSyncPending:n}){var $;const{toast:a}=ze(),o=ct(),d=($=t.note)==null?void 0:$.match(/batch(?:id)?:\s*([a-f0-9-]{36})/i),g=(d==null?void 0:d[1])||null,c=en(g),u=c==null?void 0:c.data,x=g!=null&&c!=null&&!c.isLoading&&u==null,m=(u==null?void 0:u.total)??(x?t.processed??0:t.pending_before??0),f=(u==null?void 0:u.pending)??(x?0:t.pending_after??0),p=(u==null?void 0:u.completed)??t.processed??0,v=(u==null?void 0:u.failed)??0,y=(u==null?void 0:u.skipped)??0,k=!(Date.now()-new Date(t.ran_at).getTime()>1440*60*1e3)&&!x&&(f>0||((u==null?void 0:u.processing)??0)>0),S=v>0,T=t.provider?eu[t.provider]??t.provider:"google-drive",O=t.provider?po(T,null,null).label:"Google Drive";t.pending_before,t.processed;const w=()=>t.provider?e.jsx(Wr,{sourceKind:T,tags:null,sourceRef:null,size:"sm"}):e.jsx(Nl,{className:"h-4 w-4 text-gray-400"}),b=async Q=>{if(Q.stopPropagation(),!!g)try{const{error:re}=await X.from("sync_staging").update({status:Se.FAILED,error_message:"Cancelled by user",updated_at:new Date().toISOString()}).eq("sync_batch_id",g).in("status",[Se.PENDING,Se.PROCESSING]);if(re)throw re;await o.invalidateQueries({queryKey:["sync-staging",g]}),await o.invalidateQueries({queryKey:["recent-syncs"]}),await o.invalidateQueries({queryKey:["active-sync-batches"]})}catch(re){const K=re instanceof Error?re.message:"Unknown error";a({title:"Cancel failed",description:K,variant:"destructive"})}},P=()=>k?m>0?`Syncing ${m} files from ${O}`:`Syncing from ${O}...`:S&&p===0?`Sync failed from ${O}`:S?`Partial sync from ${O}`:p>0?`Successfully synced ${p} file${p!==1?"s":""} from ${O}`:y>0?`${y} file${y!==1?"s":""} skipped (already synced) from ${O}`:`Sync from ${O}`,l=new Date(t.ran_at).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});return e.jsxs("div",{className:Ue(Ne.syncCard,S&&Ne.syncCardError,k&&Ne.syncCardProcessing),children:[e.jsxs("div",{className:Ne.syncCardLeft,children:[e.jsx("div",{className:Ne.syncStatusIcon,children:k?e.jsx(it,{className:"h-4 w-4 animate-spin"}):S?e.jsx(gs,{className:"h-4 w-4"}):e.jsx(js,{className:"h-4 w-4"})}),e.jsx("div",{className:Ne.syncProviderIcon,children:w()})]}),e.jsxs("div",{className:Ne.syncCardContent,children:[e.jsx("div",{className:Ne.syncCardTitle,children:P()}),k?e.jsx(si,{processed:p+y+v,total:m,failed:v,currentFileName:u==null?void 0:u.currentFileName,variant:"full"}):y===m&&m>0?e.jsx("div",{className:Ne.syncCardMeta,children:e.jsxs("span",{className:Ne.syncCardProgress,children:["All ",m," file",m!==1?"s":""," already synced"]})}):e.jsxs("div",{className:Ne.syncCardMeta,children:[p>0&&e.jsxs("span",{className:Ne.syncStatCompleted,children:[e.jsx(js,{className:"h-3 w-3"}),p]}),y>0&&e.jsxs("span",{className:Ne.syncStatSkipped,children:[e.jsx(Sl,{className:"h-3 w-3"}),y]}),v>0&&e.jsxs("span",{className:Ne.syncStatFailed,children:[e.jsx(Ss,{className:"h-3 w-3"}),v]}),e.jsx("span",{className:Ne.syncCardDate,children:l})]})]}),e.jsxs("div",{className:Ne.syncCardActions,children:[k&&g&&e.jsx("button",{onClick:Q=>void b(Q),className:Ue(Ne.syncActionBtn,Ne.syncActionBtnIcon),title:"Cancel sync","aria-label":"Cancel sync",children:e.jsx(at,{className:"h-4 w-4"})}),S&&!k&&e.jsxs("button",{onClick:()=>s(g),disabled:n,className:Ue(Ne.syncActionBtn,Ne.syncActionRetry),title:"Retry failed","aria-label":`Retry failed sync from ${O}`,children:[e.jsx(Zt,{className:"h-3.5 w-3.5"}),"Retry"]})]})]})}function su({syncs:t,onRetry:s,onDelete:r,runSyncPending:n}){const[a,o]=i.useState(!1),{data:d,isLoading:g,error:c}=Ya(),u=new Set((d||[]).map(f=>f.batchId)),h=f=>{if(!f)return null;const p=f.match(/batch(?:id)?:\s*([a-f0-9-]{36})/i);return(p==null?void 0:p[1])||null},x=t.filter(f=>{const p=h(f.note);return p?u.has(p):!1}).length,m=t.filter(f=>{var I,M;const p=h(f.note);if(p)return!u.has(p);const v=(f.pending_after??0)>0||((I=f.note)==null?void 0:I.includes("Error")),y=(M=f.note)==null?void 0:M.includes("Queued");return!v&&!y&&(f.processed??0)>0}).length;return e.jsxs("div",{className:Ne.syncsTableContainer,children:[e.jsxs("div",{className:Ne.syncsTableHeader,children:[e.jsx("div",{className:Ne.syncsTableHeaderLeft,children:e.jsx("div",{className:Ne.syncsHeaderLabel,children:e.jsx("span",{className:Ne.syncsHeaderLabelText,children:"Recent Syncs"})})}),e.jsxs("div",{className:Ne.syncsTableHeaderRight,children:[e.jsxs("span",{className:Ne.syncsSummaryText,children:[g?e.jsx(it,{className:"h-3 w-3 animate-spin inline-block mr-1"}):c?e.jsx(gs,{className:"h-3 w-3 inline-block mr-1",style:{color:"var(--color-error, #ef4444)"}}):null,x," active, ",m," completed"]}),e.jsx("button",{onClick:()=>o(!a),className:Ne.syncsCollapseBtn,"aria-label":a?"Expand recent syncs":"Collapse recent syncs","aria-expanded":!a,children:a?e.jsx(Vs,{className:"h-4 w-4"}):e.jsx(Pa,{className:"h-4 w-4"})})]})]}
5),!a&&e.jsx("div",{className:Ne.syncsTableBody,children:t.length===0?e.jsxs("div",{className:Ne.syncsEmptyState,children:[e.jsx(on,{className:"h-10 w-10 text-soft-muted",strokeWidth:1}),e.jsx("h2",{className:"text-lg font-semibold",children:"No recent syncs"}),e.jsx("p",{children:"Connect an integration and sync content to see activity here"})]}):e.jsx("div",{className:Ne.syncsList,children:t.map((f,p)=>{var y;const v=(y=f.note)==null?void 0:y.match(/batch: ([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i);return v&&v[1],e.jsx(tu,{sync:f,onRetry:I=>s(f,I),onDelete:I=>r(f,I),runSyncPending:n},p)})})})]})}const ru={google:{source:"google_drive"},trello:{source:"trello"},notion:{source:"notion"},dropbox:{source:"dropbox"},hubspot:{source:"hubspot"}};async function nu(t){const{count:s,error:r}=await X.from("kb_documents").select("*",{count:"exact",head:!0}).eq("is_active",!0).contains("source_ref",ru[t]);return r?(W("useLibraryCounts",r,`Failed to count ${t} docs:`),null):s??0}function au(t){var r;if(t.provider!=="google")return!0;const s=(r=t.syncConfig)==null?void 0:r.google;if(!s)return!1;if(s.mode==="include"){const n=Array.isArray(s.folders)&&s.folders.length>0,a=Array.isArray(s.files)&&s.files.length>0;return n||a}return!0}function iu(t){var r;if(t.provider!=="google")return null;const s=(r=t.syncConfig)==null?void 0:r.google;if((s==null?void 0:s.mode)==="include"){const n=Array.isArray(s.folders)?s.folders.length:0,a=Array.isArray(s.files)?s.files.length:0;return n+a||null}return null}function ou(t){var r;if(t.provider!=="trello")return null;const s=(r=t.syncConfig)==null?void 0:r.trello;return(s==null?void 0:s.mode)==="include"&&Array.isArray(s.boards)?s.boards.length:null}function ri(t){var r;if(t.provider!=="dropbox")return!0;const s=(r=t.syncConfig)==null?void 0:r.dropbox;return s?s.sync_all===!0?!0:Array.isArray(s.folders)&&s.folders.length>0:!1}function lu(t){var r;if(t.provider!=="dropbox")return null;const s=(r=t.syncConfig)==null?void 0:r.dropbox;return(s==null?void 0:s.sync_all)===!0?null:Array.isArray(s==null?void 0:s.folders)?s.folders.length:null}function cu(t){var r,n;if(t.provider!=="hubspot")return null;const s=(n=(r=t.syncConfig)==null?void 0:r.hubspot)==null?void 0:n.object_types;return Array.isArray(s)&&s.length>0?s.length:null}function du(t){const[s,r]=i.useState(new Map);return i.useEffect(()=>{if(!t)return;(async()=>{const a=new Map,o=["google","trello","notion","dropbox","hubspot"];for(const d of o)if(t.find(c=>c.provider===d&&c.connected)){const c=await nu(d);c!==null&&a.set(d,c)}r(a)})()},[t]),s}const Er=200,uu="MMM d, yyyy 'at' h:mm a",mu=["google","trello","slack","notion","dropbox","hubspot","webhook","email"];function fu(t){return t!==null&&mu.includes(t)}const hu=["google","dropbox","trello","notion","hubspot"];function hn(t){return hu.includes(t)}const pu=["google","trello","hubspot"];function gu(t){return pu.includes(t)}const St={IDLE:"idle",STARTING:"starting",RUNNING:"running",COMPLETED_WITH_ISSUES:"completed_with_issues",FAILED:"failed"};function gr(t){return t.kind===St.FAILED||t.kind===St.COMPLETED_WITH_ISSUES}function pn(t){if(t.isSyncing){const r=t.progress;return!r||r.total<=0?{kind:St.STARTING,label:"Sync starting…"}:{kind:St.RUNNING,label:"Syncing right now",processed:r.processed,total:r.total,currentFileName:r.currentFileName}}const s=t.lastSyncOutcome;if(s&&s.failed>0){const r=s.failed,n=`The last sync couldn't bring in ${r} item${r===1?"":"s"}.`,a="Try syncing again. If it keeps failing, reconnect this app.";return s.completed>0?{kind:St.COMPLETED_WITH_ISSUES,tone:"warning",label:n,detail:a,completed:s.completed,failed:s.failed,skipped:s.skipped}:{kind:St.FAILED,tone:"error",label:n,detail:a,failed:s.failed}}return{kind:St.IDLE}}function xu(t){if(!t.connected)return null;const s=pn(t);
5if(s.kind==="starting")return{kind:"syncing",label:s.label};if(s.kind==="running")return{kind:"syncing",label:s.label,progress:t.progress};if(gr(s))return{kind:"problem",tone:s.tone,label:`${s.label} ${s.detail}`};if(t.syncStatus===vt.ERROR)return{kind:"problem",tone:"error",label:"The last sync did not finish. Try syncing again, and reconnect if it keeps failing."};if(t.syncStatus===vt.REAUTH_REQUIRED)return{kind:"problem",tone:"warning",label:"Your connection expired. Reconnect to start syncing again."};if(t.syncStatus===vt.DISABLED)return{kind:"problem",tone:"warning",label:"Syncing is turned off for this connection. Reconnect to turn it back on."};if(!t.lastSync)return{kind:"never",label:"Not synced yet"};const r=os(t.lastSync,uu,"");if(!r)return{kind:"never",label:"Not synced yet"};const n=t.libraryCount,a=typeof n=="number"?` · ${n} item${n===1?"":"s"} in your library`:"";return{kind:"ok",label:`Last successful sync ${r}${a}`}}function zn(t,s){return s?t==="google"?iu(s):t==="trello"?ou(s):t==="dropbox"?lu(s):t==="hubspot"?cu(s):null:null}function qn(t,s){return typeof s=="number"?`${t} (${s})`:t}function yu(t,s){return{overview:gu(t)?qn("In your library",s.isSyncing?null:s.libraryCount):"Overview",scope:qn("What syncs",s.scopeCount)}}const vu=6e4;function bu(t,s){if(!s)return!1;const r=new Date(t).getTime(),n=new Date(s).getTime();return Number.isNaN(r)||Number.isNaN(n)?!1:n-r>vu}function wu(t){if(!t.connected)return{kind:"notConnected",title:"Connect this app first, then choose what to sync."};const s=pn(t);
5if(s.kind==="starting")return{kind:"syncStarting",title:s.label,detail:"Items appear here as they finish."};if(s.kind==="running")return{kind:"syncing",title:"Sync in progress. Items appear here as they finish.",detail:`${s.processed} of ${s.total} checked so far.`};if(gr(s))return{kind:"syncFailed",title:s.label,detail:s.detail,action:{label:"Try again",intent:"syncNow"}};const r=t.selectionNoun??"folder",n=t.selectionCount??0;if(n<=0)return{kind:"noSelection",title:"You haven't chosen anything to sync yet.",detail:"Pick what you want pulled into your library.",action:{label:"Choose what syncs",intent:"openScope"}};const a=`${n} ${r}${n===1?"":"s"}`;if(!t.lastSync||bu(t.lastSync,t.scopeSavedAt))return{kind:"notPulledYet",title:`${a} set to sync. Nothing has been pulled in yet.`,action:{label:"Sync now",intent:"syncNow"}};const o=(t.selectionNames??[]).filter(Boolean);return{kind:"foundNothing",title:`The last sync didn't find any supported files in ${o.length>0?_u(o):`the ${r}s you selected`}.`,detail:"Add files there, or change what syncs.",action:{label:"Change what syncs",intent:"openScope"}}}function _u(t,s=3){return t.length===0?"":t.length===1?t[0]:t.length<=s?`${t.slice(0,-1).join(", ")} and ${t[t.length-1]}`:`${t.slice(0,s).join(", ")} and ${t.length-s} more`}function gn(t,s){return t<Er||typeof s!="number"||s<=t?null:`Showing the ${t} most recent of ${s} items`}const Gn="We couldn't bring this file in.",Vn={[go.MAX_RETRIES_EXCEEDED]:"We tried several times and still couldn't bring this file in."},Kn={[ht.UP_TO_DATE]:"Already up to date, so nothing changed.",[ht.CONTENT_DUPLICATE]:"This file is identical to one already in your library.",[ht.SOURCE_DOC_DELETED]:"You deleted this file from your library, so it wasn't brought back in.",[ht.TITLE_COLLISION]:"Another file with a very similar name is already in your library."},ju=[{match:["cancelled by user","canceled by user"],copy:"You cancelled this sync before this file finished."},{match:["permission","forbidden","403","access denied","unauthorized"],copy:"We no longer have permission to open this file."},{match:["expired","reauth","invalid_grant","401"],copy:"The connection to this app expired. Reconnect it and sync again."},{match:["not found","404","no longer exists","was deleted"],copy:"This file was moved or deleted where it lives."},{match:["rate limit","429","too many requests","quota"],copy:"The app was busy. Try again in a few minutes."},{match:["timeout","timed out","etimedout","deadline"],copy:"This file took too long to bring in."},{match:["too large","file size","exceeds","payload too large","413"],copy:"This file is too large to bring in."},{match:["unsupported","mime","cannot export","not exportable"],copy:"We can't read this kind of file yet."},{match:["empty","no text","no extractable"],copy:"We couldn't find any readable text in this file."},{match:["password","encrypted","protected"],copy:"This file is password protected, so we couldn't open it."},{match:["network","fetch failed","econnreset","socket","dns"],copy:"We couldn't reach the app. Try again."},{match:["500","502","503","504","internal server error"],copy:"The app had a problem on its end. Try again."}];function xr(t,s){const r=t==null?void 0:t[s];return typeof r=="string"&&r.length>0?r:null}function Ir(t,s){const r=xr(s,Bt.SKIP_REASON);if(r&&Kn[r])return Kn[r];const n=xr(s,Bt.FAILURE_REASON);if(n&&Vn[n])return Vn[n];const a=(t??"").trim();if(!a)return r?"This file was skipped.":Gn;const o=a.toLowerCase();for(const{match:d,copy:g}of ju)if(d.some(c=>o.includes(c)))return g;return Gn}function Su(t,s){const r=xr(t,s);return r?`"${r}"`:null}function ni(t,s){const r=t??null,n=xr(r,Bt.SKIP_REASON),a=Su(r,"existing_title");switch(n){case ht.UP_TO_DATE:return{label:"Up to date",detail:"Already up to date.",needsDecision:!1};case ht.CONTENT_DUPLICATE:return{label:"Duplicate",detail:a?`Identical to ${a}. Nothing new to add.`:"Identical to a document already in your library. Nothing new to add.",needsDecision:!1};case ht.SOURCE_DOC_DELETED:return{label:"Deleted at the source",detail:"Deleted in Google Drive.",needsDecision:!1};
5case ht.TITLE_COLLISION:return{label:"Needs a decision",detail:a?`Looks like a new version of ${a}. What should we do?`:s?`"${s}" looks like a new version of a document you already have. What should we do?`:"Looks like a new version of a document you already have. What should we do?",needsDecision:!0};default:return{label:"Skipped",detail:Ir(null,r),needsDecision:!1}}}function ai({stagingId:t,fileName:s,existingTitle:r,existingDocId:n,onResolved:a,size:o="sm"}){const{toast:d}=ze(),g=id(),c=Za(),[u,h]=i.useState(null),[x,m]=i.useState(!1),f=o==="sm"?"sm":"default",p=u!==null,v="Finishing your last choice",y=i.useCallback(()=>{h(null),a==null||a()},[a]),I=i.useCallback(S=>{h(S),g.mutate({staging_id:t,action:S},{onSuccess:()=>{y(),d(S===Hs.REPLACE?{title:"Replacing…",description:r?`"${s}" becomes the current version of "${r}".`:`"${s}" becomes the current version.`,variant:"success"}:{title:"Keeping both. Syncing now.",description:`"${s}" comes in as its own document.`,variant:"success"})},onError:T=>{h(null),Je(d,T,S===Hs.REPLACE?"replacing that document":"keeping both documents")}})},[r,s,y,g,t,d]),M=i.useCallback(()=>{h("ignore"),c.mutate(t,{onSuccess:()=>{y()},onError:S=>{h(null),Je(d,S,"ignoring that file")}})},[c,y,t,d]),k=`Replace ${r?`'${r}'`:"the existing document"} with the Google Drive file '${s}'? The old version stays in version history. Future edits in Google Drive will update this document.`;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex shrink-0 items-center gap-1","data-existing-doc-id":n||void 0,children:[e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"utility",size:f,loading:u==="replace",disabled:p&&u!=="replace",disabledReason:p?v:void 0,"aria-label":`Replace the existing document with ${s}`,onClick:()=>m(!0),children:"Replace"})}),e.jsx(Ct,{side:"bottom",children:"Make this the current version"})]}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"utility",size:f,loading:u==="keep_both",disabled:p&&u!=="keep_both",disabledReason:p?v:void 0,"aria-label":`Keep both documents and bring in ${s}`,onClick:()=>I(Hs.KEEP_BOTH),children:"Keep both"})}),e.jsx(Ct,{side:"bottom",children:"Bring it in as a separate document"})]}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"utility",size:f,loading:u==="ignore",disabled:p&&u!=="ignore",disabledReason:p?v:void 0,"aria-label":`Ignore the skipped file ${s}`,onClick:M,children:"Ignore"})}),e.jsx(Ct,{side:"bottom",children:"Stop asking about this file"})]})]}),e.jsx(nt,{open:x,onOpenChange:m,tier:"form",maxWidth:"sm",title:"Replace with the newer file?",isLoading:u==="replace",footer:e.jsx("div",{className:"flex justify-end gap-2",children:e.jsx(q,{type:"button",variant:"primary",size:"sm",loading:u==="replace","aria-label":`Confirm replacing with ${s}`,onClick:()=>{m(!1),I(Hs.REPLACE)},children:"Replace"})}),children:e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-muted)"},children:k})})]})}function ii({selectedCount:t,actionLabel:s,actionIcon:r,onAction:n,isRunning:a=!1,progressText:o=null,onClear:d,actionVariant:g="destructive",selectionLabel:c}){return t<=0?null:e.jsxs("div",{className:"px-4 py-2 border-b border-white/10 flex items-center gap-3 flex-wrap",style:{backgroundColor:"rgba(255,255,255,0.04)"},children:[e.jsx("span",{className:"text-sm font-medium",style:{color:"var(--platform-text-primary)"},children:c??`${t} selected`}),e.jsxs(q,{variant:g,size:"sm",onClick:n,loading:a,children:[e.jsx(r,{className:"h-3 w-3"}),s]}),e.jsxs(q,{variant:"ghost",size:"sm",onClick:d,disabled:a,children:[e.jsx(at,{className:"h-3 w-3"}),"Clear"]}),o?e.jsx("span",{className:"text-xs",style:{color:"var(--platform-text-muted)"},"aria-live":"polite","aria-atomic":"true",children:o}):null]})}function Nu(t){const s=xu({...t,isSyncing:!1,lastSyncOutcome:null});return!s||s.kind==="syncing"?null:s.kind==="problem"?e.jsxs("p",{className:"mt-1.5 flex items-start gap-1.5 text-xs",style:{color:s.tone==="error"?"var(--color-error, #ef4444)":"var(--color-warning, #f59e0b)"},children:[e.jsx(Et,{className:"mt-0.5 h-3.5 w-3.5 shrink-0","aria-hidden":!0}),e.jsx("span",{children:s.label})]}):e.jsx("p",{className:"mt-1.5 text-xs",style:{color:"var(--platform-text-muted)"},children:s.label})}function xn({onOpenScope:t,onSyncNow:s,isSyncing:r=!1,...n}){var c,u;const a={...n,isSyncing:r},o=wu(a),d=((c=o.action)==null?void 0:c.intent)==="openScope"?t:((u=o.action)==null?void 0:u.intent)==="syncNow"?s:void 0,g=o.kind==="syncStarting"||o.kind==="syncing";return e.jsxs("div",{className:"flex flex-col items-start gap-2 py-6",children:[g?e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--gold)"},"aria-hidden":!0}):o.kind==="syncFailed"?e.jsx(Et,{className:"h-6 w-6",style:{color:"var(--color-error, #ef4444)"},"aria-hidden":!0}):e.jsx(on,{className:"h-6 w-6",style:{color:"var(--platform-text-muted)"},"aria-hidden":!0}),e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-primary)"},"aria-live":g?"polite":void 0,children:o.title}),o.detail?e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:o.detail}):null,o.action&&d?e.jsx(q,{variant:"secondary",size:"sm",className:"mt-1",onClick:d,disabled:o.action.intent==="syncNow"&&r,disabledReason:o.action.intent==="syncNow"&&r?"A sync is already running":void 0,children:o.action.label}):null]})}const ku={background:"rgba(245, 158, 11, 0.10)",border:"1px solid rgba(245, 158, 11, 0.25)"},Cu={background:"var(--green)",border:"1px solid var(--gold)"},Eu={background:"rgba(239, 68, 68, 0.10)",border:"1px solid rgba(239, 68, 68, 0.25)"};function yr(t,s,r){return t===1?s:r}function Wn({expanded:t,onToggle:s,children:r,tone:n="muted"}){const a=t?Vs:Ts;return e.jsxs("button",{type:"button",onClick:s,"aria-expanded":t,className:"inline-flex items-center gap-1 rounded text-xs underline-offset-2 hover:underline",style:{color:n==="primary"?"var(--platform-text-primary)":"var(--platform-text-muted)"},children:[e.jsx(a,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),r]})}function Yn({issue:t,onRetry:s,isRetrying:r}){return e.jsxs("li",{className:"flex items-start justify-between gap-3 py-1.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-xs font-medium",style:{color:"var(--platform-text-primary)"},title:t.file_name,children:t.file_name}),e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:Ir(t.error_message,t.metadata)})]}),s?e.jsxs(q,{variant:"ghost",size:"sm",className:"shrink-0",onClick:()=>s(t.id),loading:r,"aria-label":`Retry ${t.file_name}`,children:[e.jsx(La,{className:"h-3 w-3","aria-hidden":!0}),"Retry"]}):null]})}function Iu({count:t,onReview:s}){return t<=0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl px-3 py-2",style:{...Cu,color:"var(--platform-text-primary)"},"data-testid":"sync-decision-bar",children:[e.jsx(Jr,{className:"h-3.5 w-3.5 shrink-0",style:{color:"var(--gold)"},"data-testid":"sync-decision-mark","aria-hidden":!0}),e.jsx("p",{className:"min-w-0 flex-1 text-xs",children:`${t} ${yr(t,"file needs","files need")} a decision. They look like documents you already have.`}),e.jsx(q,{type:"button",variant:"utility",size:"sm",className:"shrink-0",onClick:s,"aria-label":`Review ${t} ${yr(t,"file","files")} waiting on a decision`,children:"Review"})]})}function Tu(t){const s=pn(t),r=t.lastSyncOutcome??null,[n,a]=i.useState(!1),[o,d]=i.useState(!1),g=s.kind!==St.RUNNING&&s.kind!==St.STARTING,{data:c=[]}=Qa(g?(r==null?void 0:r.batchId)??null:null),u=fn(),h=c.filter(v=>v.status===Se.FAILED),x=c.filter(v=>v.status===Se.SKIPPED),m=gr(s)?s.failed:h.length,f=(r==null?void 0:r.skipped)??x.length,p=f>0?e.jsxs("div",{className:"mt-1.5",children:[e.jsx(Wn,{expanded:o,onToggle:()=>d(v=>!v),children:`${f} skipped · unchanged`}),o&&x.length>0?e.jsx("ul",{className:"mt-1 divide-y divide-white/5",children:x.map(v=>e.jsx(Yn,{issue:v,isRetrying:!1},v.id))}):null]}):null;if(gr(s)){const v=s.tone==="warning",y=v?ku:Eu;return e.jsx("div",{className:"rounded-xl px-3 py-2 text-xs",style:{...y,color:"var(--platform-text-primary)"},children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Et,{className:"mt-0.5 h-3.5 w-3.5 shrink-0",style:{color:v?"var(--color-warning, #f59e0b)":"var(--color-error, #ef4444)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{children:[s.label," ",s.detail]}),e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-3",children:[e.jsx(Wn,{expanded:n,onToggle:()=>a(I=>!I),tone:"primary",children:`View ${m} failed ${yr(m,"item","items")}`}),n&&h.length>0?e.jsxs(q,{variant:"secondary",size:"sm",onClick:()=>u.mutate(h.map(I=>I.id)),loading:u.isPending,"aria-label":"Retry all failed items",children:[e.jsx(La,{className:"h-3 w-3","aria-hidden":!0}),"Retry all failed"]}):null]}),n?h.length>0?e.jsx("ul",{className:"mt-1 divide-y divide-white/5",children:h.map(I=>e.jsx(Yn,{issue:I,onRetry:M=>u.mutate(M),isRetrying:u.isPending},I.id))}):e.jsx("p",{className:"mt-1",style:{color:"var(--platform-text-muted)"},children:"Loading the failed items…"}):null,p]})]})})}return s.kind===St.IDLE?!r||r.completed<=0?null:e.jsxs("div",{className:"glass-inset rounded-xl px-3 py-2",children:[e.jsxs("p",{className:"text-xs",style:{color:"var(--platform-text-primary)"},children:[`Synced ${r.completed} ${yr(r.completed,"item","items")}`,f>0?` · ${f} skipped (unchanged)`:""]}),p]}):e.jsxs("div",{className:"glass-inset rounded-xl px-3 py-2","aria-live":"polite","aria-atomic":"true",children:[e.jsxs("p",{className:"flex items-center gap-2 text-xs",style:{color:"var(--platform-text-primary)"},children:[e.jsx(it,{className:"h-3.5 w-3.5 shrink-0 animate-spin",style:{color:"var(--gold)"},"aria-hidden":!0}),e.jsx("span",{children:s.kind===St.STARTING?"Sync starting… items appear here as they finish.":"Sync in progress. Items appear here as they finish."})]}),s.kind===St.RUNNING?e.jsx(si,{variant:"compact",processed:s.processed,total:s.total,currentFileName:s.currentFileName}):null]})}function Du({connectionId:t,folderExternalId:s,folderPath:r}){const{org:n,role:a}=Ve(),d=((n==null?void 0:n.org_type)===Oe.BUSINESS||(n==null?void 0:n.org_type)===Oe.INTERNAL)&&Gs(a),{data:g=[]}=un({includeSystem:!0,enabled:d}),{data:c}
5=Ql(d?t:null,d?s:null),u=Jl();if(!d||!t)return null;const h=c?g.find(m=>m.id===c.department_id)??null:null,x=async m=>{if(m)try{await u.mutateAsync({connectionId:t,folderExternalId:s,folderPath:r??null,departmentId:m})}catch(f){W("SyncFolderDepartmentPicker",f,"Failed to save folder department rule:")}};return e.jsx(Xl,{currentDepartmentId:(c==null?void 0:c.department_id)??null,departments:g,onAssign:x,trigger:e.jsxs("button",{type:"button",className:"group flex items-center gap-1.5 cursor-pointer hover:bg-white/5 rounded px-1.5 py-1 transition-colors","aria-label":h?`Change the access group new files in this folder go to, currently ${h.name}`:"Set the access group new files in this folder go to",children:[e.jsx("span",{className:"text-xs truncate max-w-[130px]",style:{color:h?"var(--platform-text-primary)":"var(--platform-text-muted)"},children:h?h.name:"Set access"}),e.jsx(Us,{className:"h-3 w-3 text-soft-muted opacity-0 group-hover:opacity-100 transition-opacity"})]})})}const tn="Webhook test - you can delete this",Ru="simply-asking-webhook-test",Au="webhook-test";function Pu(t=new Date){const s=t.toISOString();return{documents:[{external_id:`${Ru}-${s}`,title:tn,content:`This document was created by the Simply Asking webhook setup wizard at ${s} to confirm the connection works. It is safe to delete.`,content_type:"markdown",tags:[Au],metadata:{source:"simply-asking-setup-wizard"}}]}}const Hn=JSON.stringify({documents:[{external_id:"your-system-record-id",title:"Q3 pricing policy",content:"The full text of the document.",content_type:"markdown",tags:["policy"]}]},null,2);function Lu(t){const s=t.trim();if(!s)return"The endpoint returned an empty response.";try{const r=JSON.parse(s);if(r&&typeof r=="object"&&typeof r.error=="string")return r.error}catch{}return s.slice(0,200)}const Qn=["name","credentials"],Fu={name:"Name Your Integration",credentials:"Webhook Credentials"},Ou={name:"Give your webhook integration a recognizable name",credentials:"Your webhook URL and secret for sending data"},$u="#3B82F6";function Mu({open:t,onOpenChange:s,onComplete:r,orgId:n}){const{toast:a}=ze(),{user:o}=Is(),[d,g]=i.useState("name"),[c,u]=i.useState(!1),[h,x]=i.useState(!1),[m,f]=i.useState(null),[p,v]=i.useState(""),[y,I]=i.useState(null),[M,k]=i.useState(!1),[S,T]=i.useState(!1),[O,w]=i.useState(!1);i.useEffect(()=>{t&&(g("name"),v(""),I(null),f(null),k(!1),T(!1),w(!1))},[t]);const b=Qn.indexOf(d),P=()=>d==="name"?p.trim().length>=2:d==="credentials"?!!y:!1,l=async()=>{if(!o){a({title:"Authentication Required",description:"Please sign in to create a webhook connection.",variant:"destructive"});return}u(!0);try{const{data:N,error:L}=await X.rpc("create_webhook_connection",{p_user_id:o.id,p_org_id:n,p_display_name:p.trim(),p_display_color:$u});if(L)throw L;
5const U=Array.isArray(N)?N[0]:N;if(!U)throw new Error("No data returned from webhook creation");const le={connection_id:U.connection_id,webhook_id:U.webhook_id,webhook_secret:U.webhook_secret,webhook_url:"https://auth.simplyasking.io/functions/v1/webhook-ingest"};I(le),g("credentials"),Te("Webhook connection created successfully")}catch(N){W("WebhookSetupModal",N,"Failed to create webhook connection:");const L=N instanceof Error?N.message:"Could not create webhook connection";a({title:"Failed to Create Webhook",description:L,variant:"destructive"})}finally{u(!1)}},$=async()=>{d==="name"&&!y?await l():d==="credentials"&&y&&(r(y),s(!1))},Q=async()=>{if(y)try{await navigator.clipboard.writeText(y.webhook_url),k(!0),setTimeout(()=>k(!1),2e3),a({title:"Webhook URL copied",description:"Paste it into your sending system.",variant:"success"})}catch(N){W("WebhookSetupModal",N,"Failed to copy URL:"),a({title:"Copy Failed",description:"Could not copy to clipboard",variant:"destructive"})}},re=async()=>{if(y)try{await navigator.clipboard.writeText(y.webhook_secret),T(!0),setTimeout(()=>T(!1),2e3),a({title:"Webhook secret copied",description:"Store it somewhere safe - it is shown once.",variant:"success"})}catch(N){W("WebhookSetupModal",N,"Failed to copy secret:"),a({title:"Copy Failed",description:"Could not copy to clipboard",variant:"destructive"})}},K=async()=>{try{await navigator.clipboard.writeText(Hn),w(!0),setTimeout(()=>w(!1),2e3),a({title:"Sample request body copied",description:"Send it as-is to check your integration.",variant:"success"})}catch(N){W("WebhookSetupModal",N,"Failed to copy sample body:"),a({title:"Copy Failed",description:"Could not copy to clipboard",variant:"destructive"})}},D=async()=>{if(y){x(!0),f(null);try{const N=await fetch(y.webhook_url,{method:"POST",headers:{"Content-Type":"application/json","X-Webhook-ID":y.webhook_id,Authorization:`Bearer ${y.webhook_secret}`},body:JSON.stringify(Pu())});if(N.ok)f("success"),a({title:"Test document sent to your library",description:`A document titled "${tn}" is on its way to your library.`,variant:"success"});else{f("error");const L=await N.text();a({title:"Test Failed",description:`Endpoint returned ${N.status}: ${Lu(L)}`,variant:"destructive"})}}catch(N){f("error"),W("WebhookSetupModal",N,"Webhook test failed:");const L=N instanceof Error?N.message:"Network error";a({title:"Test Failed",description:L,variant:"destructive"})}finally{x(!1)}}},E=()=>d==="name"?e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ws,{htmlFor:"webhook-name",style:{color:"var(--text-primary)"},children:"Integration Name"}),e.jsx(_s,{id:"webhook-name",placeholder:"e.g., Airtable, Salesforce, Custom CRM",value:p,onChange:N=>v(N.target.value),className:"bg-white/5 border-white/20 text-soft-bright placeholder:text-white/40",autoFocus:!0}),e.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Choose a name that helps you identify this webhook source"})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg border",style:{backgroundColor:"rgba(245, 158, 11, 0.1)",borderColor:"rgba(245, 158, 11, 0.3)"},children:[e.jsx(Et,{className:"h-5 w-5 flex-shrink-0 text-amber-400 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-amber-400",children:"Save your webhook secret now"}),e.jsx("p",{className:"text-xs mt-1",style:{color:"var(--text-muted)"},children:"The secret is only shown once and cannot be retrieved later. Store it securely in your application."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ws,{style:{color:"var(--text-primary)"},children:"Webhook URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_s,{readOnly:!0,value:(y==null?void 0:y.webhook_url)||"","aria-label":"Webhook URL",className:"bg-white/5 border-white/20 text-soft-bright font-mono text-sm"}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"secondary",size:"icon",onClick:()=>void Q(),"aria-label":"Copy URL",children:M?e.jsx(fs,{className:"h-4 w-4 text-emerald-400"}):e.jsx(sr,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Copy URL"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ws,{style:{color:"var(--text-primary)"},children:"Webhook ID"}),e.jsx(_s,{readOnly:!0,value:(y==null?void 0:y.webhook_id)||"","aria-label":"Webhook ID",className:"bg-white/5 border-white/20 text-soft-bright font-mono text-sm"}),e.jsx("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:"Include as X-Webhook-ID header in your requests"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ws,{style:{color:"var(--text-primary)"},children:"Webhook Secret"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_s,{readOnly:!0,value:(y==null?void 0:y.webhook_secret)||"","aria-label":"Webhook Secret",className:"bg-white/5 border-white/20 text-soft-bright font-mono text-sm",type:"password"}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"secondary",size:"icon",onClick:()=>void re(),"aria-label":"Copy Secret",children:S?e.jsx(fs,{className:"h-4 w-4 text-emerald-400"}):e.jsx(sr,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Copy Secret"})]})]})]}),e.jsxs("div",{className:"pt-2 border-t border-white/10 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-soft-bright",children:"What to send"}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"secondary",size:"icon",onClick:()=>void K(),"aria-label":"Copy sample request body",children:O?e.jsx(fs,{className:"h-4 w-4 text-emerald-400"}):e.jsx(sr,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Copy sample body"})]})]}),e.jsxs("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:["POST JSON to the webhook URL with the headers"," ",e.jsx("code",{className:"font-mono",children:"X-Webhook-ID"}),","," ",e.jsx("code",{className:"font-mono",children:"Authorization: Bearer <secret>"})," ","and"," ",e.jsx("code",{className:"font-mono",children:"Content-Type: application/json"}),". The body must contain a ",e.jsx("code",{className:"font-mono",children:"documents"})," ","array; each document needs"," ",e.jsx("code",{className:"font-mono",children:"external_id"}),","," ",e.jsx("code",{className:"font-mono",children:"title"})," and"," ",e.jsx("code",{className:"font-mono",children:"content"}),"."]}),e.jsx("pre",{className:"p-3 rounded-lg bg-white/5 border border-white/10 overflow-x-auto font-mono text-[11px] text-soft-bright","aria-label":"Sample request body",children:Hn})]}),e.jsxs("div",{className:"pt-2 border-t border-white/10 space-y-3",children:[e.jsx("p",{className:"text-xs font-medium text-soft-bright",children:"Optional: test endpoint"}),e.jsxs("p",{className:"text-xs",style:{color:"var(--text-muted)"},children:['Sends one real sample document titled "',tn,'" so you can confirm the whole path works. Delete it from your library afterwards.']}),e.jsxs(q,{type:"button",variant:"secondary",size:"sm",onClick:()=>void D(),disabled:!y,loading:h,children:[e.jsx(Cl,{className:"h-4 w-4"}),"Send test payload"]}),m==="success"&&e.jsxs("p",{className:"text-xs text-emerald-400 flex items-center gap-1",children:[e.jsx(js,{className:"h-3.5 w-3.5"})," Test succeeded"]}),m==="error"&&e.jsxs("p",{className:"text-xs text-red-400 flex items-center gap-1",children:[e.jsx(Ss,{className:"h-3.5 w-3.5"})," Test failed"]})]})]});return e.jsx(nt,{open:t,onOpenChange:s,title:Fu[d],description:Ou[d],icon:e.jsx(kl,{className:"h-5 w-5"}),tier:"form",maxWidth:"lg",isLoading:c,footer:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:Qn.map((N,L)=>e.jsx("div",{className:`
6                  w-2 h-2 rounded-full transition-colors
7                  ${L===b?"bg-[var(--gold)]":L<b?"bg-emerald-400":"bg-white/20"}
8                `},N))}),e.jsxs(Ye,{onClick:()=>void $(),disabled:!P()||c,isLoading:c,loadingText:"Creating...",children:[d==="name"?"Create Webhook":"Done",d==="name"&&e.jsx(Ts,{className:"h-4 w-4 ml-1"})]})]}),children:E()})}const Uu=/^(\d{1,3}\.){3}\d{1,3}(\/\d{1,2})?$/,Bu=/^([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}(\/\d{1,3})?$/,Jn=t=>["connections","webhook-settings",t];function zu(t){const s=t.trim();if(!s)return!1;if(Uu.test(s)){const[r,n]=s.split("/");if(r.split(".").map(Number).some(o=>o<0||o>255))return!1;if(n!==void 0){const o=parseInt(n,10);if(o<0||o>32)return!1}return!0}if(Bu.test(s)){const[,r]=s.split("/");if(r!==void 0){const n=parseInt(r,10);if(n<0||n>128)return!1}return!0}return!1}function qu({open:t,onOpenChange:s,connectionId:r,webhookName:n,onSecretRegenerated:a}){const{toast:o}=ze(),{user:d}=Is(),g=ct(),[c,u]=i.useState(!1),[h,x]=i.useState(!1),[m,f]=i.useState([]),[p,v]=i.useState(""),[y,I]=i.useState(null),[M,k]=i.useState(!1),[S,T]=i.useState(null),[O,w]=i.useState(!1),b=He({queryKey:Jn(r),queryFn:async()=>{const{data:E,error:N}=await X.from("user_connections").select("sync_config").eq("id",r).single();if(N)throw N;const L=E==null?void 0:E.sync_config,U=(L==null?void 0:L.allowed_ips)??[];return Array.isArray(U)?U:[]},enabled:t&&!!r,refetchOnWindowFocus:!1,retry:!1}),P=b.isLoading;i.useEffect(()=>{!t||b.data===void 0||(f(b.data),k(!1))},[t,b.data]),i.useEffect(()=>{b.error&&(W("WebhookSettingsModal",b.error,"Failed to load settings:"),o({title:"Failed to load settings",description:"Could not load webhook settings",variant:"destructive"}))},[b.error,o]),i.useEffect(()=>{t||(v(""),I(null),k(!1),T(null),w(!1))},[t]);const l=()=>{const E=p.trim();if(E){if(!zu(E)){I("Invalid IP address or CIDR range");return}if(m.includes(E)){I("This IP is already in the list");return}f([...m,E]),v(""),I(null),k(!0)}},$=E=>{f(m.filter(N=>N!==E)),k(!0)},Q=async()=>
8{if(d){u(!0);try{const{data:E,error:N}=await X.rpc("update_webhook_ip_allowlist",{p_connection_id:r,p_user_id:d.id,p_allowed_ips:m.length>0?m:null});if(N)throw N;const L=Array.isArray(E)?E[0]:E;if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.message)??"Failed to update IP allowlist");k(!1),await g.invalidateQueries({queryKey:Jn(r)}),Te("IP allowlist saved:",m)}catch(E){W("WebhookSettingsModal",E,"Failed to save settings:");const N=E instanceof Error?E.message:"Could not save settings";o({title:"Failed to save",description:N,variant:"destructive"})}finally{u(!1)}}},re=async()=>{if(d){x(!0);try{const{data:E,error:N}=await X.rpc("regenerate_webhook_secret",{p_connection_id:r,p_user_id:d.id});if(N)throw N;const L=Array.isArray(E)?E[0]:E;if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.message)??"Failed to regenerate secret");T(L.new_secret??null),a==null||a(),Te("Webhook secret regenerated")}catch(E){W("WebhookSettingsModal",E,"Failed to regenerate secret:");const N=E instanceof Error?E.message:"Could not regenerate secret";o({title:"Failed to regenerate",description:N,variant:"destructive"})}finally{x(!1)}}},K=async()=>{if(S)try{await navigator.clipboard.writeText(S),w(!0),setTimeout(()=>w(!1),2e3),o({title:"New secret copied to clipboard",variant:"success"})}catch(E){W("WebhookSettingsModal",E,"Failed to copy secret:")}},D=E=>{E.key==="Enter"&&(E.preventDefault(),l())};return e.jsx(nt,{open:t,onOpenChange:s,title:"Webhook Settings",description:`Configure security settings for ${n}`,icon:e.jsx(Tn,{className:"h-5 w-5"}),tier:"form",maxWidth:"lg",footer:e.jsxs("div",{className:"flex items-center justify-end gap-2 w-full",children:[e.jsx(Ye,{variant:"secondary",onClick:()=>s(!1),children:M?"Cancel":"Close"}),M&&e.jsx(Ye,{onClick:()=>void Q(),isLoading:c,loadingText:"Saving...",children:"Save Changes"})]}),children:P?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-muted)"}})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Tn,{className:"h-4 w-4",style:{color:"var(--text-primary)"}}),e.jsx(ws,{children:"IP Allowlist"})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border bg-blue-500/10 border-blue-500/30",children:[e.jsx(nn,{className:"h-4 w-4 flex-shrink-0 text-blue-400 mt-0.5"}),e.jsxs("div",{className:"text-sm",style:{color:"var(--text-primary)"},children:[e.jsx("p",{children:"Restrict which IP addresses can send data to this webhook. Leave empty to allow all IPs."}),e.jsx("p",{className:"mt-1 text-xs",style:{color:"var(--text-muted)"},children:"Supports IPv4, IPv6, and CIDR notation (e.g., 192.168.1.0/24)"})]})]}),m.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm",style:{color:"var(--text-primary)"},children:["Allowed IPs (",m.length,"):"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(E=>e.jsxs(yt,{variant:"secondary",className:"flex items-center gap-1 pl-2 pr-1 py-1 font-mono text-xs",children:[E,e.jsx("button",{type:"button",onClick:()=>$(E),className:"ml-1 p-0.5 rounded hover:bg-white/20 transition-colors",title:"Remove IP",children:e.jsx(at,{className:"h-3 w-3"})})]},E))})]}):e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-green-500/10",children:[e.jsx(fs,{className:"h-4 w-4 text-green-400"}),e.jsx("span",{className:"text-sm",style:{color:"var(--text-primary)"},children:"All IP addresses are currently allowed"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(_s,{placeholder:"Enter IP address or CIDR (e.g., 192.168.1.1 or 10.0.0.0/8)",value:p,onChange:E=>{v(E.target.value),I(null)},onKeyDown:D,"aria-label":"IP address or CIDR",className:"bg-white/5 border-white/20 text-soft-bright placeholder:text-white/40 font-mono text-sm"}),y&&e.jsx("p",{className:"text-xs text-red-400 mt-1",children:y})]}),e.jsxs(q,{type:"button",variant:"secondary",onClick:l,disabled:!p.trim(),children:[e.jsx(_r,{className:"h-4 w-4 mr-1"}),"Add"]})]}),m.length>0&&e.jsxs(q,{type:"button",variant:"ghost",size:"sm",onClick:()=>{f([]),k(!0)},className:"text-red-400 hover:text-red-300 hover:bg-red-400/10",children:[e.jsx(Ns,{className:"h-3.5 w-3.5 mr-1.5"}),"Clear All (Allow All IPs)"]})]}),e.jsx("div",{className:"border-t",style:{borderColor:"var(--white-10)"}}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zt,{className:"h-4 w-4",style:{color:"var(--text-primary)"}}),e.jsx(ws,{children:"Webhook Secret"})]}),S?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border bg-amber-500/10 border-amber-500/30",children:[e.jsx(Et,{className:"h-4 w-4 flex-shrink-0 text-amber-400 mt-0.5"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-medium text-amber-400",children:"Save your new secret now"}),e.jsx("p",{className:"mt-1",style:{color:"var(--text-muted)"},children:"This is the only time the secret will be shown. Your old secret is now invali
8d."})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(_s,{readOnly:!0,value:S,"aria-label":"New webhook secret",className:"bg-white/5 border-white/20 text-soft-bright font-mono text-sm flex-1"}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{type:"button",variant:"secondary",size:"icon",onClick:()=>void K(),"aria-label":"Copy secret",children:O?e.jsx(fs,{className:"h-4 w-4 text-emerald-400"}):e.jsx(sr,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Copy secret"})]})]})]}):e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm",style:{color:"var(--text-primary)"},children:"Generate a new secret if you believe the current one has been compromised."}),e.jsx(q,{type:"button",variant:"secondary",onClick:()=>void re(),loading:h,children:h?"Regenerating...":e.jsxs(e.Fragment,{children:[e.jsx(Zt,{className:"h-4 w-4"}),"Regenerate Secret"]})})]})]})]})})}const oi=({className:t,...s})=>e.jsx("nav",{role:"navigation","aria-label":"pagination",className:Ue("mx-auto flex w-full justify-center",t),...s});oi.displayName="Pagination";const li=i.forwardRef(({className:t,...s},r)=>e.jsx("ul",{ref:r,className:Ue("flex flex-row items-center gap-1",t),...s}));li.displayName="PaginationContent";const Fs=i.forwardRef(({className:t,...s},r)=>e.jsx("li",{ref:r,className:Ue("",t),...s}));Fs.displayName="PaginationItem";const Tr=({className:t,isActive:s,size:r="icon",align:n="center",...a})=>e.jsx("a",{"aria-current":s?"page":void 0,className:Ue(xo({variant:s?"utility":"ghost",size:r,align:n}),t),...a});Tr.displayName="PaginationLink";const ci=({className:t,...s})=>e.jsxs(Tr,{"aria-label":"Go to previous page",size:"default",className:Ue("gap-1 pl-2.5",t),...s,children:[e.jsx(El,{className:"h-4 w-4"}),e.jsx("span",{children:"Previous"})]});ci.displayName="PaginationPrevious";const di=({className:t,...s})=>e.jsxs(Tr,{"aria-label":"Go to next page",size:"default",className:Ue("gap-1 pr-2.5",t),...s,children:[e.jsx("span",{children:"Next"}),e.jsx(Ts,{className:"h-4 w-4"})]});di.displayName="PaginationNext";const Ur=10;function Gu(t){return t?t.charAt(0).toUpperCase()+t.slice(1):"Unknown"}function Vu({connectionId:t,connectionName:s,onClose:r}){const[n,a]=i.useState(1),{toast:o}=ze(),{data:d={docs:[],totalCount:0},isLoading:g,isFetching:c,error:u}=He({queryKey:["library-documents","connector","webhook",t,n],queryFn:async()=>{const v=(n-1)*Ur,{count:y,error:I}=await X.from("kb_documents").select("id",{count:"exact",head:!0}).eq("source_ref->>connection_id",t).eq("is_active",!0);if(I)throw I;const{data:M,error:k}=await X.from("kb_documents").select("id, title, created_at, status, source_ref").eq("source_ref->>connection_id",t).eq("is_active",!0).order("created_at",{ascending:!1}).range(v,v+Ur-1);if(k)throw k;return{docs:M||[],totalCount:y||0}},refetchOnWindowFocus:!1,retry:!1}),{docs:h,totalCount:x}=d,m=g||c,f=Math.ceil(x/Ur);i.useEffect(()=>{u&&(W("WebhookLibrary",u,"Failed to load webhook documents:"),o({title:"Failed to load documents",description:"Could not load documents for this webhook",variant:"destructive"}))},[u,o]);const p=v=>{v>=1&&v<=f&&a(v)};return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"sticky top-0 z-20 flex items-center justify-between gap-4 px-6 py-4 border-b",style:{backgroundColor:"var(--bg-secondary)",borderColor:"var(--white-10)"},children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ps,{className:"h-5 w-5",style:{color:"var(--text-primary)"}}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--text-bright)"},children:s}),e.jsxs("p",{className:"text-sm",style:{color:"var(--text-primary)"},children:[x," document",x!==1?"s":""," synced via webhook"]})]})]}),r?e.jsx(q,{variant:"ghost",size:"icon",onClick:r,"aria-label":"Close",children:e.jsx(at,{className:"h-4 w-4"})}):null]}),e.jsx("div",{className:"px-6 py-4",children:m?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-bright)"}})}):h.length===0?e.jsxs("div",{className:"flex flex-col items-start gap-2 py-6",children:[e.jsx(on,{className:"h-6 w-6",style:{color:"var(--platform-text-muted)"},"aria-hidden":!0}),e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-primary)"},children:"No documents yet"}),e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:"Documents will appear here as they arrive through this webhook connection."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border overflow-hidden",style:{borderColor:"var(--white-10)",backgroundColor:"rgba(255, 255, 255, 0.02)"},children:e.jsxs(za,{children:[e.jsx(qa,{children:e.jsxs(hr,{className:"border-b",style:{borderColor:"var(--white-10)"},children:[e.jsx(Jt,{className:"font-medium",style:{color:"var(--text-primary)"},children:"Title"}),e.jsx(Jt,{className:"font-medium",style:{color:"var(--text-primary)"},children:"Synced"}),e.jsx(Jt,{className:"font-medium",style:{color:"var(--text-primary)"},children:"Status"}),e.jsx(Jt,{className:"font-medium",style:{color:"var(--text-primary)"}
8,children:"External ID"}),e.jsx(Jt,{className:"w-[100px]"})]})}),e.jsx(Ga,{children:h.map(v=>{var y,I;return e.jsxs(hr,{className:"border-b transition-colors",style:{borderColor:"var(--white-10)"},children:[e.jsx(Xt,{children:e.jsx("div",{className:"font-medium max-w-[300px] truncate",style:{color:"var(--text-bright)"},title:v.title,children:v.title})}),e.jsx(Xt,{children:e.jsx("span",{className:"text-sm",style:{color:"var(--text-primary)"},children:new Date(v.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})})}),e.jsx(Xt,{children:e.jsx(yt,{variant:Vl(v.status??"unknown"),children:Gu(v.status)})}),e.jsx(Xt,{children:e.jsx("span",{className:"text-sm font-mono max-w-[150px] truncate block",style:{color:"var(--text-primary)"},title:((y=v.source_ref)==null?void 0:y.external_id)||"-",children:((I=v.source_ref)==null?void 0:I.external_id)||"-"})}),e.jsx(Xt,{children:e.jsxs("a",{href:`/library/${v.id}`,className:"dialog-external-link",children:[e.jsx(jr,{className:"h-3.5 w-3.5 shrink-0"}),"View"]}
8)})]},v.id)})})]})}),f>1&&e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx(oi,{children:e.jsxs(li,{children:[e.jsx(Fs,{children:e.jsx(ci,{onClick:()=>p(n-1),"aria-disabled":n===1,className:n===1?"pointer-events-none opacity-50":"cursor-pointer"})}),Array.from({length:f},(v,y)=>y+1).filter(v=>v===1||v===f||Math.abs(v-n)<=1).map((v,y,I)=>{const M=y>0&&I[y-1]!==v-1;return e.jsxs("span",{className:"flex items-center",children:[M&&e.jsx(Fs,{children:e.jsx("span",{className:"flex h-9 w-9 items-center justify-center",style:{color:"var(--text-primary)"},children:"..."})}),e.jsx(Fs,{children:e.jsx(Tr,{onClick:()=>p(v),isActive:v===n,className:"cursor-pointer",children:v})})]},v)}),e.jsx(Fs,{children:e.jsx(di,{onClick:()=>p(n+1),"aria-disabled":n===f,className:n===f?"pointer-events-none opacity-50":"cursor-pointer"})})]})})})]})})]})}function Ku(t){const s=t.filter(n=>n.type==="folder").map(n=>n.id),r=t.filter(n=>n.type==="file").map(n=>n.id);return{google:{mode:"include",folders:s,files:r,selections:t}}}async function ui(t){const s=Ku(t);return await br({provider:"google",syncConfig:s}),{folderIds:s.google.folders,fileIds:s.google.files}}const Wu="AIzaSyBaEPy8uqSC1DJDyo6g5QV-6o5Ol8xNnS4";function Yu(){return new Promise((t,s)=>{var n;if((n=window.google)!=null&&n.picker){t();return}if(window.gapi){window.gapi.load("picker",()=>t());return}const r=document.createElement("script");r.src="https://apis.google.com/js/api.js",r.async=!0,r.defer=!0,r.onload=()=>{window.gapi.load("picker",()=>t())},r.onerror=()=>s(new Error("Failed to load Google API script")),document.head.appendChild(r)})}function Hu({onSelect:t,onError:s}){var x;const{orgId:r}=Ve(),[n,a]=i.useState(!1),[o,d]=i.useState(!!((x=window.google)!=null&&x.picker)),[g,c]=i.useState(!1),u=i.useRef(null);return{openPicker:i.useCallback(async()=>{a(!0);try{await Yu(),d(!0);const m=await yo(r??void 0);if(m.error||!m.access_token)throw new Error(m.error||"Failed to get Drive access token");const f=window.google;if(!(f!=null&&f.picker))throw new Error("Google Picker API failed to load");const p=new f.picker.DocsView().setIncludeFolders(!0).setSelectFolderEnabled(!0).setParent("root"),v=new f.picker.DocsView().setIncludeFolders(!0).setSelectFolderEnabled(!0).setEnableDrives(!0),y=new f.picker.DocsView(f.picker.ViewId.RECENTLY_PICKED),I=new f.picker.PickerBuilder().setDeveloperKey(Wu).setOAuthToken(m.access_token).setAppId(m.app_id).addView(p).addView(v).addView(y).enableFeature(f.picker.Feature.MULTISELECT_ENABLED).enableFeature(f.picker.Feature.SUPPORT_DRIVES).setTitle("Select files and folders to sync").setCallback(M=>{if(M.action===f.picker.Action.PICKED&&M.docs){const k=M.docs.map(S=>({id:S.id,name:S.name,mimeType:S.mimeType,type:S.mimeType==="application/vnd.google-apps.folder"?"folder":"file"}));t(k),c(!1)}else M.action===f.picker.Action.CANCEL&&c(!1)}).build();u.current=I,c(!0),I.setVisible(!0)}catch(m){const f=m instanceof Error?m.message:"Unknown error";W("useGooglePicker",m,"Failed to open picker:"),s==null||s(f)}finally{a(!1)}},[t,s,r]),isLoading:n,isReady:o,pickerVisible:g}}const Qu=/(personal|photos?|tax|finance|family|private|medical|health|diary|journal)/i;function Ju({open:t,onOpenChange:s,connection:r,onDisconnect:n,isDisconnecting:a,variant:o="dialog",autoOpenPicker:d,onSaved:g,pickerOpenSignal:c=0}){const{toast:u}=ze(),h=ct(),x=Cs(),{orgId:m}=Ve(),{mutate:f}=dn({silent:!0}),[p,v]=i.useState([]),[y,I]=i.useState(!1),M=i.useRef(!1),k=i.useRef([]);i.useEffect(()=>{k.current=p},[p]);const[S,T]=i.useState(new Set),[O,w]=i.useState(!1),[b,P]=i.useState(null);i.useEffect(()=>{var F;if(t&&((F=r==null?void 0:r.syncConfig)!=null&&F.google)){const Y=r.syncConfig.google;if(Array.isArray(Y.selections)&&Y.selections.length>0)v(Y.selections);else{const ie=Array.isArray(Y.folders)?Y.folders:[],oe=ie.map((C,A)=>({id:C,name:ie.length===1?"Synced Folder":`Synced Folder ${A+1}`,mimeType:"application/vnd.google-apps.folder",type:"folder"}));v(oe)}}},[t,r]);const l=i.useCallback(async F=>{const Y=await ui(F);return h.invalidateQueries({queryKey:["connections"]}),g==null||g(),Y},[h,g]),$=i.useCallback(async(F,Y)=>{const ie=F.length-Y.length;I(!0);try{await l(F),f({provider:"google",orgId:m,departmentId:null}),u({title:`Added ${ie} item${ie!==1?"s":""} from Google Drive`,description:"Syncing now…",variant:"success",action:e.jsx(pa,{altText:"View activity",onClick:()=>x(qt.UPLOAD_ACTIVITY),children:"View activity"})})}catch(oe){v(Y),W("DrivePickerModal",oe,"Failed to save sync config:"),Je(u,oe,"adding items from Google Drive")}finally{I(!1)}},[l,f,m,u,x]),Q=i.useCallback(F=>{if(F.find(te=>te.id==="root")){u({title:"Can't sync your entire Drive",description:"Pick specific work folders instead. Syncing My Drive root would share every file in your Drive with your organization, including personal files.",variant:"destructive"});return}const ie=F.filter(te=>te.type==="folder"&&Qu.test(te.name));ie.length>0&&u({title:"Heads up — folder names look personal",description:`${ie.map(te=>`"${te.name}"`).join(", ")} suggests personal content. Double-check before continuing.`});const oe=k.current,C=new Set(oe.map(te=>te.id)),A=F.filter(te=>!C.has(te.id));if(A.length===0){u({title:"Already selected",description:"All selected items are already in your sync list."});return}const B=[...oe,...A];v(B),$(B,oe)},[u,$]),re=i.useCallback(F=>{u({title:"Google Drive Picker Error",description:F,variant:"destructive"})},[u]),{openPicker:K,isLoading:D,pickerVisible:E}=Hu({onSelect:Q,onError:re});i.useEffect(()=>{t&&d&&!M.current&&(M.current=!0,K()),t||(M.current=!1)},[t,d,K]);const N=i.useRef(c);i.useEffect(()=>{c!==N.current&&(N.current=c,!(!t||c<=0)&&K())},[c,t,K]),i.useEffect(()=>{T(F=>{if(F.size===0)return F;const Y=new Set(p.map(oe=>oe.id)),ie=new Set([...F].filter(oe=>Y.has(oe)));return ie.size===F.size?F:ie})},[p]);const L=async F=>{const Y=p;if(!Y.some(oe=>oe.id===F))return;
8const ie=Y.filter(oe=>oe.id!==F);P(F);try{await l(ie),v(ie)}catch(oe){W("DrivePickerModal",oe,"Failed to remove from sync:"),Je(u,oe,"removing an item from sync")}finally{P(null)}},U=F=>{T(Y=>{const ie=new Set(Y);return ie.has(F)?ie.delete(F):ie.add(F),ie})},Z=()=>{T(F=>p.length>0&&p.every(ie=>F.has(ie.id))?new Set:new Set(p.map(ie=>ie.id)))},le=async()=>{if(S.size===0)return;const F=p.filter(ie=>S.has(ie.id)).length;if(F===0)return;const Y=p.filter(ie=>!S.has(ie.id));w(!0);try{await l(Y),v(Y),T(new Set),u({title:"Removed from sync",description:`${F} item${F!==1?"s":""} will no longer sync. Documents already in your library stay.`,variant:"success"})}catch(ie){W("DrivePickerModal",ie,"Failed to bulk remove from sync:"),Je(u,ie,"removing items from sync")}finally{w(!1)}},De=t&&!E;i.useEffect(()=>{t&&d&&!E&&M.current&&p.length===0&&!D&&s(!1)},[t,d,E,p.length,D,s]);const fe=p.filter(F=>F.type==="folder").length,ye=p.filter(F=>F.type==="file").length,pe=p.length>0&&p.every(F=>S.has(F.id)),de=e.jsxs("div",{className:"p-6 space-y-4",children:[e.jsx(q,{variant:"primary",size:"lg",className:"w-full",onClick:()=>void K(),disabled:D||y||O,loading:D||y,children:D?"Loading Google Drive...":e.jsxs(e.Fragment,{children:[e.jsx(_r,{className:"h-4 w-4"}),p.length>0?"Add more":"Add from Google Drive"]})}),p.length>0&&e.jsxs("div",{className:"overflow-hidden rounded-2xl border border-white/10",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 border-b border-white/10 p-4",children:[e.jsxs("span",{className:"text-sm font-medium",style:{color:"var(--platform-text-primary)"},children:["Syncing from (",p.length,")"]}),e.jsxs("span",{className:"text-sm shrink-0",style:{color:"var(--platform-text-muted)"},children:[fe>0&&`${fe} folder${fe!==1?"s":""}`,fe>0&&ye>0&&", ",ye>0&&`${ye} file${ye!==1?"s":""}`]})]}),e.jsx(ii,{selectedCount:S.size,actionLabel:"Remove from sync",actionIcon:at,onAction:()=>void le(),isRunning:O,onClear:()=>T(new Set)}),e.jsx("div",{className:"max-h-[400px] overflow-auto",children:e.jsxs(za,{children:[e.jsx(qa,{children:e.jsxs(hr,{className:"hover:bg-transparent border-b border-white/10 bg-[rgba(255,255,255,0.02)]",children:[e.jsx(Jt,{className:"w-10",children:e.jsx(Vt,{checked:pe,onCheckedChange:Z,disabled:O||p.length===0,"aria-label":"Select all synced items"})}),e.jsx(Jt,{className:"text-[0.6875rem] font-semibold uppercase tracking-[0.1em]",style:{color:"var(--platform-text-muted)"},children:"Name"}),e.jsx(Jt,{className:"text-[0.6875rem] font-semibold uppercase tracking-[0.1em]",style:{color:"var(--platform-text-muted)"},children:"Type"}),e.jsx(Jt,{className:"w-16 text-right text-[0.6875rem] font-semibold uppercase tracking-[0.1em]",style:{color:"var(--platform-text-muted)"},children:"Actions"})]})}),e.jsx(Ga,{children:p.map(F=>e.jsxs(hr,{className:"transition-colors border-b border-white/10 hover:bg-white/5","data-state":S.has(F.id)?"selected":void 0,children:[e.jsx(Xt,{className:"w-10",children:e.jsx(Vt,{checked:S.has(F.id),onCheckedChange:()=>U(F.id),disabled:O,"aria-label":`Select ${F.name}`})}),e.jsx(Xt,{children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[F.type==="folder"?e.jsx(ln,{className:"h-4 w-4 shrink-0",style:{color:"var(--gold)"},"aria-hidden":!0}):e.jsx(rr,{className:"h-4 w-4 shrink-0",style:{color:"var(--platform-text-muted)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-soft-primary truncate",title:F.name,children:F.name}),F.type==="folder"&&e.jsx("div",{className:"text-xs text-soft-secondary",children:"Everything in it syncs, including files added later."})]})]})}),e.jsx(Xt,{children:e.jsx("span",{className:"text-xs text-soft-secondary whitespace-nowrap",children:F.type==="folder"?"Folder":Xu(F.mimeType)})}),e.jsx(Xt,{children:e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",onClick:()=>void L(F.id),disabled:O||b!==null,loading:b===F.id,"aria-label":`Remove ${F.name}`,children:e.jsx(at,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Remove"})]})})})]},F.id))})]})})]}),p.length===0&&!d&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[e.jsx(Xr,{className:"h-10 w-10 mb-3",style:{color:"var(--platform-text-muted)"}}),e.jsx("p",{className:"text-sm font-medium mb-1",style:{color:"var(--platform-text-primary)"},children:"No files or folders selected"}),e.jsx("p",{className:"text-xs max-w-xs",style:{color:"var(--platform-text-muted)"},children:'Click "Add from Google Drive" to choose folders and files. They sync as soon as you pick them.'})]})]});return o==="picker-only"?null:o==="inline"?t?de:null:e.jsx(nt,{open:De,onOpenChange:s,title:"Manage Google Drive Sync",description:"Select files and folders from Google Drive to sync into your knowledge base",icon:e.jsx(Xr,{className:"h-5 w-5"}),tier:"form",maxWidth:"2xl",isLoading:y,contentClassName:"!p-0",footer
8:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsxs(q,{type:"button",variant:"ghost",onClick:()=>{n(),s(!1)},disabled:a||y,loading:a,className:"text-sm text-soft-muted hover:text-soft-primary",children:[e.jsx(Sr,{className:"h-3.5 w-3.5"}),a?"Disconnecting...":"Disconnect Google Drive"]}),e.jsx(Ye,{variant:"secondary",onClick:()=>s(!1),disabled:y,children:"Done"})]}),children:de})}function Xu(t){return{"application/vnd.google-apps.document":"Google Doc","application/vnd.google-apps.spreadsheet":"Google Sheet","application/vnd.google-apps.presentation":"Google Slides","application/vnd.google-apps.form":"Google Form","application/pdf":"PDF","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"Word Document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"Excel Spreadsheet","application/vnd.openxmlformats-officedocument.presentationml.presentation":"PowerPoint","text/plain":"Text File","text/csv":"CSV","text/html":"HTML"}[t]||"File"}function Zu({crumbs:t,onNavigate:s}){return t.length===0?null:e.jsx("nav",{"aria-label":"Drive folders","data-testid":"drive-breadcrumb",children:e.jsx("ol",{className:"flex flex-wrap items-center gap-1",children:t.map((r,n)=>{const a=n===t.length-1;return e.jsxs("li",{className:"flex items-center gap-1",children:[n>0&&e.jsx(Ts,{className:"h-3.5 w-3.5 shrink-0",style:{color:"var(--platform-text-muted)"},"aria-hidden":"true"}),a?e.jsx("span",{"aria-current":"page",className:"max-w-[16rem] truncate text-sm font-medium",style:{color:"var(--platform-text-primary)"},title:r.label,children:r.label}):e.jsx("button",{type:"button",onClick:()=>s(r.id),"aria-label":`Go to ${r.label}`,title:r.label,className:Ue("max-w-[16rem] truncate rounded px-1 text-sm","hover:text-[var(--gold)] focus-visible:outline-none","focus-visible:ring-1 focus-visible:ring-[var(--gold)]"),style:{color:"var(--platform-text-secondary)"},children:r.label})]},r.id??"__root__")})})})}const Xn={needs_decision:6,failed:5,syncing:4,skipped:3,synced_updated:2,up_to_date:1},em=new Set(["up_to_date","synced_updated"]),Br="__other__",tm="Other synced files",sm=1440*60*1e3,rm=60*1e3;function nr(t){return(t==null?void 0:t.source_ref)??{}}function Dt(t){return typeof t=="string"&&t.length>0?t:void 0}function nm(t){var r;if(!t||t.status!==Se.SKIPPED)return;const s=Dt((r=t.metadata)==null?void 0:r[Bt.SKIP_REASON]);return s&&vo.includes(s)?s:void 0}function Gt(t){if(!t)return null;const s=new Date(t).getTime();return Number.isFinite(s)?s:null}function am(t,s){const r=Gt(t),n=Gt(s);return r===null?s:n===null||r>=n?t:s}function $s(t){const s=nr(t);return il({lastSyncedAt:Dt(s.last_synced_at),updatedAt:t.updated_at,createdAt:t.created_at,importedAt:Dt(s.imported_at)})}function yn(t){return t.processed_at??t.created_at}function im(t,s){if(!s)return!0;const r=Gt(yn(t)),n=Gt($s(s));return r===null||n===null?!0:r>=n}function om(t){const s=t.metadata??{},r=Dt(s.skip_reason);return r===ht.TITLE_COLLISION?!!Dt(s.resolved_at)||!!Dt(s.dismissed_at)?"up_to_date":"needs_decision":r===ht.UP_TO_DATE||r===ht.CONTENT_DUPLICATE?"up_to_date":"skipped"}function lm(t,s){const r=Gt(t.created_at),n=Gt(t.updated_at);if(!(r!==null&&n!==null&&n>r+rm))return"up_to_date";const o=Gt($s(t));return o===null?"up_to_date":s-o<=sm?"synced_updated":"up_to_date"}function cm(t,s,r){if(s&&im(s,t))switch(s.status){case Se.PENDING:case Se.PROCESSING:return"syncing";case Se.FAILED:return"failed";case Se.SKIPPED:return om(s)}return t?lm(t,r):"skipped"}function dm(t){let s,r=-1/0;for(const n of t){if(!n.sync_batch_id)continue;const a=Gt(yn(n));if(a===null)return n.sync_batch_id;a>r&&(r=a,s=n.sync_batch_id)}return s}function um(t,s,r){return!r||t.sync_batch_id===r?!0:s==="needs_decision"||s==="failed"||s==="syncing"}function mm({selections:t,docs:s,staging:r,now:n=new Date}){var M,k,S,T,O;const a=n.getTime(),o=t.filter(w=>w.type==="folder"),d=t.filter(w=>w.type==="file"),g=new Map(t.map(w=>[w.id,w])),c=new Map;for(const w of r)w.external_id&&(c.has(w.external_id)||c.set(w.external_id,w));const u=new Map;for(const w of r)w.doc_id&&w.external_id&&!u.has(w.doc_id)&&u.set(w.doc_id,w.external_id);const h=new Map;for(const w of s){const b=Dt(nr(w).external_id)??u.get(w.id);if(!b)continue;const P=h.get(b);(!P||(Gt($s(w))??0)>(Gt($s(P))??0))&&h.set(b,w)}const x=dm(r),m=new Set([...h.keys(),...c.keys()]),f=[];for(const w of m){const b=h.get(w),P=c.get(w),l=Dt(nr(b).selection_root_id),$=Dt((M=P==null?void 0:P.metadata)==null?void 0:M.selection_root_id),Q=l??$,re=Q&&g.has(Q)?Q:void 0,K=cm(b,P,a),D=g.has(w)||re!==void 0;if(!b&&P&&!D&&!um(P,K,x))continue;const E=(b==null?void 0:b.title)??(P==null?void 0:P.file_name)??((k=g.get(w))==null?void 0:k.name)??"Untitled",N=b?$s(b):P?yn(P):null;f.push({external_id:w,doc:b,staging:P,selection_root_id:re,syncStatus:K,skipReason:nm(P),lastSyncedAt:N,title:E,webViewLink:Dt(nr(b).url)??Dt((P==null?void 0:P.web_view_link)??void 0),isSelectionRoot:((S=g.get(w))==null?void 0:S.type)==="file"})}f.sort((w,b)=>w.title.localeCompare(b.title));const p=new Map,v=(w,b)=>{const P=p.get(w);P?P.push(b):p.set(w,[b])};for(const w of f){if(w.isSelectionRoot){v(w.external_id,w);continue}const b=w.selection_root_id;if(b&&((T=g.get(b))==null?void 0:T.type)==="folder"){v(b,w);continue}v(Br,w)}const y=[];for(const w of o)y.push(zr(w.id,w.name,"folder",p.get(w.id)??[],fm(w.id)));for(const w of d){const b=p.get(w.id)??[];b.length!==0&&y.push(zr(w.id,w.name,"file",b,(O=b[0])==null?void 0:O.webViewLink))}const I=p.get(Br)??[];return I.length>0&&y.push(zr(Br,tm,"other",I)),{groups:y,rows:f}}function fm(t){return`https://drive.google.com/drive/folders/${t}`}function zr(t,s,r,n,a){return{id:t,title:s,kind:r,rowIds:n.map(o=>o.external_id),lastSyncedAt:n.reduce((o,d)=>am(o,d.lastSyncedAt),null),externalUrl:a,statusRollup:hm(n)}}function hm(t){let s="up_to_date",r=0;for(const n of t)Xn[n.syncStatus]>Xn[s]&&(s=n.syncStatus),em.has(n.syncStatus)||(r+=1);return{worst:s,nonGreenCount:r}}const qr=["library-documents","connector","google_drive"],Gr=4,Zn="id,title,doc_type,updated_at,created_at,tags,source_ref,source_kind,org_type,org_id,department_id,created_by,version_number,processing_state",pm=[{value:"all",label:"All files"},{value:"attention",label:"Needs attention"}],gm="Google Drive";function xm({variant:t="dialog",connection:s,onAddFromDrive:r,onRowsSummary:n,totalCount:a=null,
8selectionCount:o=null,selectionNames:d,lastSync:g=null,scopeSavedAt:c=null,selectionNoun:u="folder",isSyncing:h=!1,progress:x,lastSyncOutcome:m=null,libraryRefreshKey:f=null,onOpenScope:p,onSyncNow:v}){const{toast:y}=ze(),{orgId:I}=Ve(),M=ct(),[k,S]=i.useState(new Set),[T,O]=i.useState(!1),[w,b]=i.useState(null),[P,l]=i.useState(null),[$,Q]=i.useState(null),[re,K]=i.useState(!1),[D,E]=i.useState(""),[N,L]=i.useState("all"),[U,Z]=i.useState(null),[le,De]=i.useState("title"),[fe,ye]=i.useState(null),[pe,de]=i.useState(null),[F,Y]=i.useState(null),[ie,oe]=i.useState(!1),[C,A]=i.useState(new Set),{mutate:B}=dn(),te=fn(),{data:he=[],isLoading:ue,error:Ae}=un({includeSystem:!0}),Ce=[...qr,I],{data:xe=[],isLoading:$e,error:se,refetch:ke}=He({queryKey:Ce,queryFn:async()=>{const{data:_,error:z}=await X.from("kb_documents").select(Zn).eq("is_active",!0).contains("source_ref",{source:"google_drive"}).order("updated_at",{ascending:!1}).limit(Er);if(z)throw z;return _||[]},refetchOnWindowFocus:!1,retry:!1}),{data:Ee=[],isLoading:Xe,error:bt}=ld((s==null?void 0:s.id)??null),Qe=i.useMemo(()=>{const _=new Set(xe.map(H=>H.id)),z=new Set;for(const H of Ee)H.doc_id&&!_.has(H.doc_id)&&z.add(H.doc_id);return Array.from(z).sort()},[xe,Ee]),{data:dt=[],isLoading:Kt,error:pt}=He({queryKey:[...qr,I,"by-id",Qe],queryFn:async()=>{if(Qe.length===0)return[];const{data:_,error:z}=await X.from("kb_documents").select(Zn).eq("is_active",!0).in("id",Qe);if(z)throw z;return _||[]},enabled:Qe.length>0,refetchOnWindowFocus:!1,retry:!1}),Ze=i.useMemo(()=>dt.length>0?[...xe,...dt]:xe,[xe,dt]),Ie=i.useMemo(()=>{var _,z;return((z=(_=s==null?void 0:s.syncConfig)==null?void 0:_.google)==null?void 0:z.selections)??[]},[s]),{groups:ot,rows:Be}=i.useMemo(()=>mm({selections:Ie,docs:Ze,staging:Ee}),[Ie,Ze,Ee]),Wt=i.useMemo(()=>Be.filter(_=>{var z;return _.syncStatus==="needs_decision"&&!!((z=_.staging)!=null&&z.id)}),[Be]),wt=Wt.length,_t=i.useMemo(()=>pe?Wt.filter(_=>{var H;const z=(H=_.staging)==null?void 0:H.id;return!z||C.has(z)?!1:pe.stagingId?pe.stagingId===z:!0}):[],[Wt,C,pe]),At=i.useCallback(_=>{A(new Set),de({stagingId:_})},[]);i.useEffect(()=>{pe&&_t.length===0&&de(null)},[pe,_t.length]),i.useEffect(()=>{pt&&W("GoogleDriveLibrary",pt,"Failed to load documents by id:")},[pt]),i.useEffect(()=>{se&&(W("GoogleDriveLibrary",se,"Failed to load Google library:"),y({title:"Failed to load items",description:"Could not load Google Drive items",variant:"destructive"}))},[se,y]),i.useEffect(()=>{S(_=>{const z=new Set(Ze.map(je=>je.id)),H=new Set([..._].filter(je=>z.has(je)));return H.size===_.size?_:H})},[Ze]);const gt=i.useRef(f);i.useEffect(()=>{f!==gt.current&&(gt.current=f,f&&M.invalidateQueries({queryKey:qr}))},[f,M]),i.useEffect(()=>{Z(null)},[s==null?void 0:s.id]);const xt=i.useRef(null);i.useEffect(()=>{n&&xt.current!==Be.length&&(xt.current=Be.length,n({driveFiles:Be.length}))},[n,Be.length]);const jt=i.useCallback(_=>{var je,st,Ge;const z=Qo(_.syncStatus,_.skipReason),H={status:_.syncStatus,label:z.label,lastSyncedAt:_.lastSyncedAt,visible:z.visible,mark:z.mark};if(((je=_.staging)==null?void 0:je.status)===Se.SKIPPED){const Re=ni(_.staging.metadata,_.title);return{...H,label:Re.needsDecision?Re.label:H.label,detail:_.skipReason===ht.UP_TO_DATE?void 0:Re.detail}}return _.syncStatus==="failed"?{...H,detail:Ir((st=_.staging)==null?void 0:st.error_message,(Ge=_.staging)==null?void 0:Ge.metadata)}:H},[]),ut=i.useCallback(_=>N==="all"||_.syncStatus==="needs_decision"||_.syncStatus==="failed",[N]),Pt=D.trim().toLowerCase(),It=Pt.length>0,G=i.useMemo(()=>{const _=new Map;for(const z of ot)for(const H of z.rowIds)_.set(H,z.id);return _},[ot]),ne=i.useMemo(()=>{const _=new Map;for(const z of Be){if(!z.doc)continue;const H=G.get(z.external_id);if(!H)continue;const je=_.get(H);je?je.push(z.doc.id):_.set(H,[z.doc.id])}return _},[Be,G]),ce=i.useMemo(()=>new Map(ot.map(_=>[_.id,_])),[ot]),J=i.useMemo(()=>Be.filter(_=>ut(_)&&(!Pt||_.title.toLowerCase().includes(Pt))),[Be,ut,Pt]),ve=i.useCallback(_=>le==="lastSynced"?[..._].sort((z,H)=>new Date(H.lastSyncedAt??0).getTime()-new Date(z.lastSyncedAt??0).getTime()):[..._].sort((z,H)=>z.title.localeCompare(H.title)),[le]),{levelGroups:Pe,levelRows:qe}=i.useMemo(()=>
8{if(It||U){const Re=U?J.filter($t=>G.get($t.external_id)===U):J;return{levelGroups:[],levelRows:ve(Re)}}const _=ot.some(Re=>Re.kind==="folder"),z=Re=>Re.kind==="folder"||Re.kind==="other"&&_,H=new Set(J.map(Re=>Re.external_id)),je=new Map,st=[];for(const Re of J){const $t=G.get(Re.external_id),ss=$t?ce.get($t):void 0;if(!ss||!z(ss)){st.push(Re);continue}je.set(ss.id,(je.get(ss.id)??0)+1)}return{levelGroups:ot.filter(z).filter(Re=>N==="all"||(je.get(Re.id)??0)>0).map(Re=>({...Re,rowIds:Re.rowIds.filter($t=>H.has($t))})).sort((Re,$t)=>Re.title.localeCompare($t.title)),levelRows:ve(st)}},[It,U,J,G,ce,ot,N,ve]);i.useEffect(()=>{U&&!ce.has(U)&&Z(null)},[U,ce]);const mt=U?ce.get(U):void 0,et=i.useMemo(()=>[{id:null,label:gm},...mt?[{id:mt.id,label:mt.title}]:[]],[mt]),Tt=i.useMemo(()=>{const _=new Map;for(const z of Be)z.doc&&_.set(z.doc.id,z);return _},[Be]),Yt=i.useMemo(()=>qe.map(_=>_.doc).filter(_=>!!_),[qe]),ft=i.useMemo(()=>qe.filter(_=>!_.doc),[qe]),j=i.useMemo(()=>new Map,[]),ee=i.useMemo(()=>{const _=new Map;for(const z of qe)_.set(z.doc?z.doc.id:z.external_id,jt(z));return _},[qe,jt]),me=i.useCallback((_,z)=>{ye(z),B({provider:"google",orgId:I,departmentId:null,externalIds:_},{onSettled:()=>ye(null)})},[I,B]),Le=async(_,z)=>{const H=Ie.filter(je=>je.id!==_);K(!0);try{await ui(H),M.invalidateQueries({queryKey:["connections"]}),z.length>0&&(await Lt(z),await ke()),z.length>0&&y({title:`${z.length} document${z.length===1?"":"s"} deleted from your library`,variant:"success"})}catch(je){W("GoogleDriveLibrary",je,"Failed to remove from sync:"),Je(y,je,"removing an item from sync")}finally{K(!1),Q(null)}},tt=_=>{if(_.length===0)return;const z=new Set(_);M.setQueryData(Ce,H=>H&&H.filter(je=>!z.has(je.id)))},Lt=async _=>{const z=[];let H=0;for(const je of Yl(_,Gr)){const st=await Promise.all(je.map(async Ge=>{try{return await Ms({doc_id:Ge}),{docId:Ge,ok:!0}}catch(Re){return W("GoogleDriveLibrary",Re,`Failed to delete document ${Ge}:`),{docId:Ge,ok:!1}}}));tt(st.filter(Ge=>Ge.ok).map(Ge=>Ge.docId)),z.push(...st.filter(Ge=>!Ge.ok).map(Ge=>Ge.docId)),H+=je.length,b({dispatched:Math.min(H+Gr,_.length),total:_.length})}return z},Ht=async()=>{const _=Array.from(k);if(_.length!==0){O(!0),b({dispatched:Math.min(Gr,_.length),total:_.length});try{const z=await Lt(_),H=_.length-z.length;z.length===0?y({title:`Removed ${H} item${H===1?"":"s"} from your library`,variant:"success"}):y({title:"Partial success",description:`Removed ${H} item${H===1?"":"s"}, ${z.length} failed`,variant:"destructive"}),S(new Set(z)),await ke()}catch(z){W("GoogleDriveLibrary",z,"Failed to bulk delete documents:"),Je(y,z,"removing those items")}finally{O(!1),b(null)}}},es=()=>{P&&(l(null),Ht())},ge=async _=>{try{const z=await bo({doc_id:_});if(z!=null&&z.url){window.open(z.url,"_blank");return}window.open(wo(_),"_blank")}catch(z){W("GoogleDriveLibrary",z,"Error resolving original via doc-url:")}},Ft=_=>{S(z=>{const H=new Set(z);return H.has(_)?H.delete(_):H.add(_),H})},Ke=()=>{S(_=>Yt.length>0&&Yt.every(H=>_.has(H.id))?new Set:new Set(Yt.map(H=>H.id)))},Qt=_=>_?e.jsx(Mt,{asChild:!0,children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(jr,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Open in Drive"]})}):null,Ds=_=>{const z=new Set(_.rowIds);return Be.filter(H=>z.has(H.external_id)&&H.doc).map(H=>H.doc.id)},Dr=_=>_.kind!=="folder"?null:e.jsxs(ir,{children:[e.jsx(or,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon","aria-label":`More actions for ${_.title}`,children:e.jsx(mr,{className:"h-4 w-4"})})}),e.jsxs(lr,{align:"end",className:"w-52",children:[e.jsxs(Mt,{disabled:h||fe!==null,onSelect:()=>me([_.id],_.id),"aria-label":`Sync ${_.title}`,children:[e.jsx(Zt,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Sync now"]}),Qt(_.externalUrl),xs(_,Ds(_))]})]}),ts=_=>_.kind==="folder"?e.jsx(Du,{connectionId:s==null?void 0:s.id,folderExternalId:_.id,folderPath:_.title}):null,Ws=(_,z)=>e.jsxs(Mt,{disabled:h||fe!==null,onSelect:()=>me(_,z),children:[e.jsx(Zt,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Re-sync from Drive"]}),xs=(_,z)=>e.jsxs(Mt,{onSelect:()=>Q({group:_,docIds:z}),"aria-label":`Remove ${_.title} from sync`,children:[e.jsx(at,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Remove from sync"]}),ys=_=>_.isSelectionRoot?ot.find(z=>z.id===_.external_id):void 0,vn=_=>{const z=Tt.get(_.id);if(!z)return null;const H=ys(z);return e.jsxs(e.Fragment,{children:[Qt(z.webViewLink),Ws([z.external_id],z.external_id),H&&xs(H,[_.id])]})},bn=_=>{var st;const z=(st=_.staging)==null?void 0:st.id,H=ys(_),je=_.syncStatus==="failed"&&!!z;return e.jsxs(ir,{children:[e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(or,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon","aria-label":`More actions for ${_.title}`,children:e.jsx(mr,{className:"h-4 w-4"})})})}),e.jsx(Ct,{children:"More actions"})]}),e.jsxs(lr,{align:"end",className:"w-52",children:[je&&z&&e.jsxs(Mt,{disabled:te.isPending,onSelect:()=>te.mutate(z),"aria-label":`Retry ${_.title}`,children:[e.jsx(Aa,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Retry"]}),_.syncStatus==="needs_decision"&&z&&e.jsxs(Mt,{onSelect:()=>At(z),"aria-label":`Resolve ${_.title}`,children:[e.jsx(Jr,{className:"mr-2 h-4 w-4","aria-hidden":"true"}),"Resolve…"]}),Qt(_.webViewLink),Ws([_.external_id],_.external_id),H&&xs(H,[])]})]})},Rr=_=>bn(_),Ys=gn(xe.length,a),ls=Be.length>0||Ie.length>0,Rs=$e||(Xe||Kt)&&xe.length===0?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-bright)"}})}):ls?e.jsxs(e.Fragment,{children:[e.jsx(Iu,{count:wt,onReview:()=>At(null)}),e.jsx(Tu,{isSyncing:h,progress:x,lastSyncOutcome:m}),bt&&e.jsxs("p",{className:"flex items-center gap-1.5 text-sm",style:{color:"var(--platform-text-muted)"},children:[e.jsx(Et,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Sync status is temporarily unavailable. Documents are still listed."]}),Ae&&!ue&&e.jsxs("p",{className:"flex items-center gap-1.5 text-sm",style:{color:"var(--platform-text-muted)"},children:[e.jsx(Et,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Access group names are temporarily unavailable. Files are still listed."]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-white/10 bg-white/[0.02]",children:[e.jsx(Hl,{searchValue:D,onSearchChange:E,searchPlaceholder:"Search f
8iles...",sortOptions:[{value:"title",label:"Name"},{value:"lastSynced",label:"Last synced"}],sortValue:le,onSortChange:_=>De(_==="lastSynced"?"lastSynced":"title"),trailing:e.jsx("div",{className:"flex flex-wrap items-center gap-1",role:"group","aria-label":"Filter files",children:pm.map(_=>e.jsx(q,{variant:"utility",size:"sm","data-active":N===_.value,"aria-pressed":N===_.value,onClick:()=>L(_.value),children:_.label},_.value))})}),Ys&&e.jsx("p",{className:"px-4 pt-2 text-xs",style:{color:"var(--platform-text-muted)"},children:Ys}),e.jsx(ii,{selectedCount:k.size,actionLabel:"Delete",actionIcon:Ns,onAction:()=>l({kind:"bulk",count:k.size}),isRunning:T,progressText:w?`Removing ${w.dispatched} of ${w.total}…`:null,onClear:()=>S(new Set)})]}),It?e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},"data-testid":"drive-search-scope",children:"Showing results across all folders"}):e.jsx(Zu,{crumbs:et,onNavigate:Z}),e.jsx("div",{children:e.jsx(Jo,{documents:Yt,selectedIds:k,onToggleSelect:Ft,onSelectAll:Ke,onOpen:_=>void ge(_.id),onPreview:_=>{Y({..._,updated_at:_.updated_at||_.created_at}),oe(!0)},onDelete:()=>void ke(),fallbackOrgType:"business",groups:Pe,groupIdByRowKey:j,groupDocIds:ne,renderGroupActions:Dr,onNavigateGroup:_=>Z(_.id),syncStatusById:ee,extraRows:ft,renderExtraRowActions:Rr,renderDocRowMenuItems:vn,renderGroupLibraryAs:ts,departments:he,actionsLayout:"compact",presentation:"browser",columns:{syncStatus:!0,lastSynced:!0}})})]}):e.jsx(xn,{connected:!0,selectionCount:o,selectionNames:d,lastSync:g,scopeSavedAt:c,selectionNoun:u,isSyncing:h,progress:x,lastSyncOutcome:m,onOpenScope:r??p,onSyncNow:v}),Ot=e.jsx(Ba,{open:P!==null,onOpenChange:_=>{_||l(null)},title:P?`Remove ${P.count} item${P.count===1?"":"s"} from your library?`:"Remove these items from your library?",description:"Permanently delete these documents from your knowledge base. Originals in Google Drive stay unchanged.",confirmLabel:"Remove",onConfirm:es}),Me=e.jsx(nt,{open:$!==null,onOpenChange:_=>{!_&&!re&&Q(null)},title:$?`Stop syncing "${$.group.title}"?`:"Stop syncing?",description:"New and changed files in it will no longer come in.",tier:"form",maxWidth:"sm",isLoading:re,icon:e.jsx(at,{className:"h-5 w-5","aria-hidden":!0}),footer:e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[$&&$.docIds.length>0&&e.jsx(Ye,{variant:"destructive",disabled:re,onClick:()=>void Le($.group.id,$.docIds),children:`Remove and delete the ${$.docIds.length} document${$.docIds.length===1?"":"s"}`}),e.jsx(Ye,{variant:"primary",disabled:re,onClick:()=>$&&void Le($.group.id,[]),children:"Stop syncing"})]}),children:e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-secondary)"},children:$&&$.docIds.length>0?`Its ${$.docIds.length} document${$.docIds.length===1?"":"s"} stay in your library.`:"Documents already in your library stay."})}),Ar=e.jsx(nt,{open:pe!==null,onOpenChange:_=>{_||de(null)},tier:"form",maxWidth:"lg",title:_t.length===1?"1 file needs a decision":`${_t.length} files need a decision`,description:"Each of these looks like a document you already have. Choose what should happen to it.",icon:e.jsx(Jr,{className:"h-5 w-5","aria-hidden":!0}),children:e.jsx("ul",{className:"divide-y divide-white/5","data-testid":"sync-decision-list",children:_t.map(_=>{var st;const z=_.staging.id,H=(st=_.staging)==null?void 0:st.metadata,je=typeof(H==null?void 0:H.existing_title)=="string"?H.existing_title:void 0;return e.jsxs("li",{className:"flex items-center gap-3 py-3","data-testid":`sync-decision-item-${_.external_id}`,children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",style:{color:"var(--platform-text-primary)"},title:_.title,children:_.title}),je&&e.jsx("p",{className:"truncate text-xs",style:{color:"var(--platform-text-muted)"},children:je===_.title?"same name as a document you already have":`looks like: ${je}`})]}),e.jsx(ai,{stagingId:z,fileName:_.title,existingTitle:je,existingDocId:typeof(H==null?void 0:H.existing_doc_id)=="string"?H.existing_doc_id:void 0,size:"md",onResolved:()=>A(Ge=>new Set(Ge).add(z))})]},z)})})});return e.jsxs("div",{className:t==="inline"?"w-full min-w-0 space-y-5":"w-full min-w-0",children:[Rs,Ot,Me,Ar,F&&e.jsx(Xo,{open:ie,onOpenChange:oe,document:F})]})}const ym=t=>["connections","trello-boards",t??"none"];function vm({open:t,onOpenChange:s,connection:r,onSave:n,preferSaveAndSync:a=!1,variant:o="dialog"}){const{toast:d}=ze(),g=ct(),c=Ks(),[u,h]=i.useState(new Set),[x,m]=i.useState(!1),f=He({queryKey:ym(r==null?void 0:r.id),queryFn:async()=>{var T;const S=await _o();if(S!=null&&S.error){const O=typeof S.error=="string"?S.error:((T=S.error)==null?void 0:T.message)||"Could not retrieve boards from Trello",w=S.details?typeof S.details=="string"?S.details:JSON.stringify(S.details):"",b=typeof S.hint=="string"?S.hint:"";let P=O;throw w&&typeof w=="string"&&(w.includes("reconnect")||w.includes("permission")||w.includes("disconnect")?P=w:w.length<150&&(P=`${O}: ${w}`)),b&&(P=`${P}. ${b}`),new Error(P)}return(S==null?void 0:S.boards)||[]},enabled:t,refetchOnWindowFocus:!1,retry:!1}),p=f.data??[],v=f.isLoading||f.isFetching;i.useEffect(()=>{var S,T;t&&((T=(S=r==null?void 0:r.syncConfig)==null?void 0:S.trello)!=null&&T.boards?h(new Set(r.syncConfig.trello.boards)):h(new Set))},[t,r]),i.useEffect(()=>{if(!f.error)return;W("BoardSelectionModal",f.error,"Failed to list boards:");const S=f.error instanceof Error?f.error.message:"";S!=null&&S.includes("authenticated")||d({title:"Failed to load boards",de
8scription:S||"Could not retrieve boards from Trello",variant:"destructive",duration:5e3})},[f.error,d]),i.useEffect(()=>{!t||v||f.error||!f.data||p.length===0&&d({title:"No boards found",description:"No boards found in your Trello account. Create a board to sync.",variant:"warning"})},[p.length,v,f.data,f.error,t,d]);const y=S=>{h(T=>{const O=new Set(T);return O.has(S)?O.delete(S):O.add(S),O})},I=async()=>{m(!0);try{const S={trello:{mode:"include",boards:Array.from(u)}};await br({provider:"trello",syncConfig:S}),s(!1),g.invalidateQueries({queryKey:["connections"]}),n==null||n()}catch(S){W("BoardSelectionModal",S,"Failed to save sync config:"),Je(d,S,"saving board settings")}finally{m(!1)}},M=()=>{r&&(c.mutate(r.provider),s(!1))},k=e.jsx("div",{className:"space-y-1 max-h-[500px] overflow-auto p-6",style:{color:"var(--text-bright)"},children:v?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-bright)"}})}):e.jsxs(e.Fragment,{children:[p.length===0&&e.jsx("p",{className:"text-sm",style:{color:"var(--text-primary)"},children:"No boards found."}),p.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs",style:{color:"var(--text-primary)"},children:u.size>0?`${u.size} board${u.size!==1?"s":""} selected`:"No boards selected"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>{u.size===p.length?h(new Set):h(new Set(p.map(S=>S.id)))},className:"text-xs h-7",style:{color:"var(--text-bright)"},children:u.size===p.length?"Deselect All":"Select All"})})]}),p.map(S=>{const T=u.has(S.id);return e.jsxs("label",{className:`dialog-selection-row ${T?"selected":""}`,children:[e.jsx(Vt,{checked:T,onCheckedChange:()=>y(S.id),className:"mt-1 cursor-pointer"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[S.color&&e.jsx("div",{className:"w-4 h-4 rounded",style:{backgroundColor:S.color},title:"Board color"}),e.jsx("span",{className:"font-medium text-sm",style:{color:"var(--text-bright)"},children:S.name})]}),S.desc&&e.jsx("p",{className:"text-xs line-clamp-2 mb-1",style:{color:"var(--text-primary)"},children:S.desc}),e.jsxs("div",{className:"flex items-center gap-4 text-xs",style:{color:"var(--text-primary)"},children:[S.cardsCount>0&&e.jsxs("span",{children:[S.cardsCount," card",S.cardsCount!==1?"s":""]}),S.membersCount>0&&e.jsxs("span",{children:[S.membersCount," member",S.membersCount!==1?"s":""]}),S.url&&e.jsx("a",{href:S.url,target:"_blank",rel:"noopener noreferrer",onClick:O=>O.stopPropagation(),className:"underline hover:text-white",style:{color:"var(--text-primary)"},children:"View on Trello"})]})]})]},S.id)})]})]})});return o==="inline"?t?e.jsxs(e.Fragment,{children:[k,e.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-white/10 px-6 py-4",children:[e.jsx(Ye,{variant:"secondary",onClick:()=>s(!1),disabled:x,children:"Cancel"}),e.jsx(Ye,{onClick:()=>void I(),disabled:x||v,isLoading:x,loadingText:"Saving...",children:a?"Save & Sync":"Save"})]})]}):null:e.jsx(nt,{open:t,onOpenChange:s,title:"Manage Trello Boards",description:"Choose which boards from your Trello account should be synced to Simply Asking",icon:e.jsx(ya,{className:"h-5 w-5"}),tier:"form",maxWidth:"2xl",isLoading:x||v,contentClassName:"!p-0",footer:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx(q,{type:"button",variant:"ghost",onClick:M,disabled:x,loading:c.isPending,className:"text-sm text-soft-muted hover:text-soft-primary",children:c.isPending?"Disconnecting...":e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-3.5 w-3.5"}),"Disconnect Trello"]})}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ye,{onClick:()=>void I(),disabled:x||v,isLoading:x,loadingText:"Saving...",children:a?"Save & Sync":"Save"})})]}),children:k})}const bm=["library-documents","connector","trello"];function wm({totalCount:t=null,selectionCount:s=null,selectionNames:r,lastSync:n=null,scopeSavedAt:a=null,
8selectionNoun:o="board",isSyncing:d=!1,progress:g,lastSyncOutcome:c=null,onOpenScope:u,onSyncNow:h}={}){const[x,m]=i.useState(null),[f,p]=i.useState(new Set),[v,y]=i.useState(!1),{toast:I}=ze(),{orgId:M}=Ve(),{data:k=[],isLoading:S,error:T,refetch:O}=He({queryKey:[...bm,M],queryFn:async()=>{const{data:D,error:E}=await X.from("kb_documents").select("id,title,doc_type,updated_at,created_at,tags,source_ref,org_type").eq("is_active",!0).contains("source_ref",{source:"trello"}).order("updated_at",{ascending:!1}).limit(Er);if(E)throw E;return D||[]},refetchOnWindowFocus:!1,retry:!1});i.useEffect(()=>{T&&(W("TrelloLibrary",T,"Failed to load Trello library:"),I({title:"Failed to load items",description:"Could not load Trello cards",variant:"destructive"}))},[T,I]),i.useEffect(()=>{p(D=>{const E=new Set(k.map(L=>L.id)),N=new Set([...D].filter(L=>E.has(L)));return N.size===D.size?D:N})},[k]);const w=D=>{p(E=>{const N=new Set(E);return N.has(D)?N.delete(D):N.add(D),N})},b=()=>{f.size===k.length?p(new Set):p(new Set(k.map(D=>D.id)))},P=()=>{p(new Set)},l=k.length>0&&f.size===k.length,$=f.size>0,Q=async D=>{if(confirm("Are you sure you want to remove this item from your library? This will delete the document and cannot be undone.")){m(D);try{await Ms({doc_id:D}),await O(),p(E=>{const N=new Set(E);return N.delete(D),N})}catch(E){W("TrelloLibrary",E,"Failed to delete document:");const N=E instanceof Error?E.message:"Unknown error";I({title:"Failed to remove item",description:N||"Could not remove the item",variant:"destructive"})}finally{m(null)}}},re=async()=>{const D=f.size;if(D!==0&&confirm(`Are you sure you want to remove ${D} item${D>1?"s":""} from your library? This will delete the documents and cannot be undone.`)){y(!0);try{const E=Array.from(f);let N=0,L=0;for(const U of E)try{await Ms({doc_id:U}),N++}catch(Z){W("TrelloLibrary",Z,`Failed to delete document ${U}:`),L++}I(L===0?{title:"Items removed",description:`Successfully removed ${N} item${N>1?"s":""} from your library`,variant:"success"}:{title:"Partial success",description:`Removed ${N} item${N>1?"s":""}, ${L} failed`,variant:"destructive"}),await O(),p(new Set)}catch(E){W("TrelloLibrary",E,"Failed to bulk delete documents:");const N=E instanceof Error?E.message:"Unknown error";I({title:"Failed to remove items",description:N||"Could not remove the items",variant:"destructive"})}finally{y(!1)}}};if(S)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-bright)"}})});if(!k.length)return e.jsx(xn,{connected:!0,selectionCount:s,selectionNames:r,lastSync:n,scopeSavedAt:a,selectionNoun:o,isSyncing:d,progress:g,lastSyncOutcome:c,onOpenScope:u,onSyncNow:h});const K=gn(k.length,t);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"dialog-list-toolbar",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Vt,{checked:l?!0:$?"indeterminate":!1,onCheckedChange:b,"aria-label":l?"Deselect all":"Select all",className:"cursor-pointer"}),e.jsx("span",{className:"text-sm",style:{color:"var(--text-primary)"},children:$?e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--text-bright)"},children:f.size})," ","of ",k.length," selected"]}):e.jsxs(e.Fragment,{children:[k.length," card",k.length!==1?"s":""]})}),K&&e.jsx("span",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:K})]}),$&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:P,disabled:v,className:"text-xs",children:"Clear"}),e.jsx(q,{variant:"destructive",size:"sm",onClick:()=>void re(),loading:v,className:"text-xs",children:v?"Removing...":e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3.5 w-3.5"}),"Remove ",f.size," card",f.size>1?"s":""]})})]})]}),e.jsx("div",{className:"dialog-list-container",children:k.map(D=>{var N,L;const E=f.has(D.id);return e.jsxs("div",{className:`dialog-list-row ${E?"selected":""}`,children:[e.jsx(Vt,{checked:E,onCheckedChange:()=>w(D.id),"aria-label":`Select ${D.title}`,className:"cursor-pointer shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[e.jsx("div",{className:"dialog-list-row-title",title:D.title,children:D.title}),e.jsxs("div",{className:"dialog-list-row-meta",children:[((N=D.source_ref)==null?void 0:N.board_name)&&e.jsx("span",{className:"mr-2",children:D.source_ref.board_name}),new Date(D.updated_at||D.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})]})]}),e.jsxs("div",{className:"dialog-list-row-actions",children:[((L=D.source_ref)==null?void 0:L.url)&&e.jsxs("a",{href:D.source_ref.url,target:"_blank",rel:"noopener noreferrer",className:"dialog-external-link",children:[e.jsx(jr,{className:"h-3.5 w-3.5 shrink-0"}),"View on Trello"]}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{variant:"destructive",size:"icon-sm",onClick:()=>void Q(D.id),disabled:v,loading:x===D.id,"aria-label":"Remove",children:e.jsx(Ns,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Remove"})]})]})]},D.id)})})]})}const _m=t=>["connections","dropbox-folders",t??"none"];function jm({open:t,onOpenChange:s,connection:r,onSave:n,preferSaveAndSync:a=!1,variant:o="dialog"}){const{toast:d}=ze(),g=ct(),c=Ks(),[u,h]=i.useState(new Set),[x,m]=i.useState(!1),[f,p]=i.useState(!1),v=He({queryKey:_m(r==null?void 0:r.id),queryFn:async()=>{const w=await jo();if(w!=null&&w.error)throw new Error(typeof w.error=="string"?w.error:"Could not retrieve folders from Dropbox");return(w==null?void 0:w.folders)??[]},enabled:t,refetchOnWindowFocus:!1,retry:!1}),y=v.data??[],I=v.isLoading||v.isFetching;i.useEffect(()=>{var b;if(!t)return;const w=(b=r==null?void 0:r.syncConfig)==null?void 0:b.dropbox;w!=null&&w.sync_all?(m(!0),h(new Set)):w!=null&&w.folders?(m(!1),h(new Set(w.folders))):(m(!1),h(new Set))},[t,r]),i.useEffect(()=>{if(!v.error)return;W("DropboxFolderSelectionModal",v.error,"Failed to list folders:");const w=v.error instanceof Error?v.error.message:"";w!=null&&w.includes("authenticated")||d({title:"Failed to load folders",description:w||"Could not retrieve folders from Dropbox",variant:"destructive"})},[v.error,d]),i.useEffect(()=>{!t||I||v.error||!v.data||y.length===0&&d({title:"No folders found",description:"No folders at the top of your Dropbox. You can still sync the entire account.",variant:"warning"})},[y.length,I,v.data,v.error,t,d]);const M=w=>{m(!1),h(b=>{const P=new Set(b);return P.has(w)?P.delete(w):P.add(w),P})},k=x||u.size>0,S=async()=>
8{if(!k){d({title:"Select folders",description:"Choose at least one folder, or confirm Entire Dropbox.",variant:"destructive"});return}p(!0);try{const w={dropbox:x?{sync_all:!0,folders:[]}:{sync_all:!1,folders:Array.from(u)}};await br({provider:"dropbox",syncConfig:w}),s(!1),g.invalidateQueries({queryKey:["connections"]}),n==null||n()}catch(w){W("DropboxFolderSelectionModal",w,"Failed to save sync config:"),Je(d,w,"saving Dropbox settings")}finally{p(!1)}},T=()=>{r&&(c.mutate(r.provider),s(!1))},O=e.jsx("div",{className:"space-y-3 max-h-[500px] overflow-auto p-6",style:{color:"var(--text-bright)"},children:I?e.jsx("div",{className:"flex items-center justify-center py-10",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-bright)"}})}):e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-start gap-3 p-3 rounded-lg border border-white/10 hover:bg-white/5 cursor-pointer",children:[e.jsx(Vt,{checked:x,onCheckedChange:w=>{const b=w===!0;m(b),b&&h(new Set)},className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Entire Dropbox"}),e.jsx("p",{className:"text-xs text-soft-muted",children:"Sync all supported files from the root. Use only if you intend to ingest the whole account."})]})]}),e.jsx("p",{className:"text-xs pt-2",style:{color:"var(--text-primary)"},children:"Or select specific folders"}),y.length===0?e.jsx("p",{className:"text-sm",style:{color:"var(--text-primary)"},children:"No top-level folders found."}):e.jsx("div",{className:"space-y-2",children:y.map(w=>e.jsxs("label",{className:"flex items-center gap-3 p-3 rounded-lg border border-white/10 hover:bg-white/5 cursor-pointer",children:[e.jsx(Vt,{checked:!x&&u.has(w.path),disabled:x,onCheckedChange:()=>M(w.path)}),e.jsx(Ra,{className:"h-4 w-4 shrink-0 text-soft-muted"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:w.name}),e.jsx("p",{className:"text-xs text-soft-muted truncate",children:w.path})]})]},w.path))})]})});return o==="inline"?t?e.jsxs(e.Fragment,{children:[O,e.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-white/10 px-6 py-4",children:[e.jsx(Ye,{variant:"secondary",onClick:()=>s(!1),disabled:f,children:"Cancel"}),e.jsx(Ye,{onClick:()=>void S(),disabled:f||I||!k,isLoading:f,loadingText:"Saving...",children:a?"Save & Sync":"Save"})]})]}):null:e.jsx(nt,{open:t,onOpenChange:s,title:"Choose Dropbox folders",description:"Only these folders enter your knowledge base. Subfolders are included.",icon:e.jsx(va,{className:"h-5 w-5"}),tier:"form",maxWidth:"2xl",isLoading:f||I,contentClassName:"!p-0",footer:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx(q,{type:"button",variant:"ghost",onClick:T,disabled:f,loading:c.isPending,className:"text-sm text-soft-muted hover:text-soft-primary",children:c.isPending?"Disconnecting...":e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-3.5 w-3.5"}),"Disconnect Dropbox"]})}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ye,{onClick:()=>void S(),disabled:f||I||!k,isLoading:f,loadingText:"Saving...",children:a?"Save & Sync":"Save"})})]}),children:O})}const Ps=[{id:"contacts",label:"Contacts",description:"People and leads in your CRM",icon:e.jsx(an,{className:"h-4 w-4"})},{id:"companies",label:"Companies",description:"Organizations and accounts",icon:e.jsx(cn,{className:"h-4 w-4"})},{id:"deals",label:"Deals",description:"Sales opportunities and pipelines",icon:e.jsx(Fa,{className:"h-4 w-4"})},{id:"tickets",label:"Tickets",description:"Support tickets and service requests",icon:e.jsx(Oa,{className:"h-4 w-4"})}];function Sm({open:t,onOpenChange:s,connection:r,onSave:n,preferSaveAndSync:a=!1,variant:o="dialog"}){const{toast:d}=ze(),g=ct(),c=Ks(),u=Ma(),[h,x]=i.useState(new Set),[m,f]=i.useState(!1);i.useEffect(()=>{var k,S;t&&((S=(k=r==null?void 0:r.syncConfig)==null?void 0:k.hubspot)!=null&&S.object_types)?x(new Set(r.syncConfig.hubspot.object_types)):t&&x(new Set(Ps.map(T=>T.id)))},[t,r]);const p=k=>{x(S=>{const T=new Set(S);return T.has(k)?T.delete(k):T.add(k),T})},v=async()=>{f(!0);try{const k={hubspot:{object_types:Array.from(h)}};await br({provider:"hubspot",syncConfig:k}),s(!1),g.invalidateQueries({queryKey:["connections"]}),n==null||n()}catch(k){W("ObjectTypeSelectionModal",k,"Failed to save sync config:"),Je(d,k,"saving sync settings")}finally{f(!1)}},y=()=>{r&&(c.mutate(r.provider),s(!1))},I=k=>{u.mutate({provider:"hubspot",enabled:k})},M=e.jsxs("div",{className:"space-y-1 max-h-[500px] overflow-auto p-6",style:{color:"var(--text-bright)"},children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 pb-4 border-b border-white/10",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--text-bright)"},children:"Auto-sync"}),e.jsx("p",{className:"text-xs",style:{color:"var(--text-primary)"},children:"Automatically sync new records on a schedule"})]}),e.jsx(So,{checked:(r==null?void 0:r.autoSync)??!1,onCheckedChange:I,disabled:u.isPending})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs",style:{color:"var(--text-primary)"},children:h.size>0?`${h.size} type${h.size!==1?"s":""} selected`:"No types selected"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>{h.size===Ps.length?x(new Set):x(new Set(Ps.map(k=>k.id)))},className:"text-xs h-7",style:{color:"var(--text-bright)"},children:h.size===Ps.length?"Deselect All":"Select All"})})]}),Ps.map(k=>{const S=h.has(k.id);return e.jsxs("label",{className:`dialog-selection-row ${S?"selected":""}`,children:[e.jsx(Vt,{checked:S,onCheckedChange:()=>p(k.id),className:"mt-1 cursor-pointer"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"w-6 h-6 rounded flex items-center justify-center",style:{backgroundColor:"rgba(255, 122, 89, 0.15)",color:"#FF7A59"},children:k.icon}),e.jsx("span",{className:"font-medium text-sm",style:{color:"var(--text-bright)"},children:k.label})]}),e.jsx("p",{className:"text-xs",style:{color:"var(--text-primary)"},children:k.description})]})]},k.id)})]})]});return o==="inline"?t?e.jsxs(e.Fragment,{children:[M,e.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-white/10 px-6 py-4",children:[e.jsx(Ye,{variant:"secondary",onClick:()=>s(!1),disabled:m,children:"Cancel"}),e.jsx(Ye,{onClick:()=>void v(),disabled:m,isLoading:m,loadingText:"Saving...",children:a?"Save & Sync":"Save"})]})]}):null:e.jsx(nt,{open:t,onOpenChange:s,title:"Manage HubSpot Objects",description:"Choose which CRM object types to sync from HubSpot",icon:e.jsx(ba,{className:"h-5 w-5"}),tier:"form",maxWidth:"2xl",isLoading:m,contentClassName:"!p-0",footer
8:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx(q,{type:"button",variant:"ghost",onClick:y,disabled:m,loading:c.isPending,className:"text-sm text-soft-muted hover:text-soft-primary",children:c.isPending?"Disconnecting...":e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-3.5 w-3.5"}),"Disconnect HubSpot"]})}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(Ye,{onClick:()=>void v(),disabled:m,isLoading:m,loadingText:"Saving...",children:a?"Save & Sync":"Save"})})]}),children:M})}const Nm=["library-documents","connector","hubspot"],km={contacts:e.jsx(an,{className:"h-3 w-3"}),companies:e.jsx(cn,{className:"h-3 w-3"}),deals:e.jsx(Fa,{className:"h-3 w-3"}),tickets:e.jsx(Oa,{className:"h-3 w-3"})},Cm={contacts:"Contact",companies:"Company",deals:"Deal",tickets:"Ticket"};function Em({totalCount:t=null,selectionCount:s=null,selectionNames:r,lastSync:n=null,scopeSavedAt:a=null,selectionNoun:o="record type",isSyncing:d=!1,progress:g,lastSyncOutcome:c=null,onOpenScope:u,onSyncNow:h}={}){const[x,m]=i.useState(null),[f,p]=i.useState(new Set),[v,y]=i.useState(!1),{toast:I}=ze(),{orgId:M}=Ve(),{data:k=[],isLoading:S,error:T,refetch:O}=He({queryKey:[...Nm,M],queryFn:async()=>{const{data:D,error:E}=await X.from("kb_documents").select("id,title,doc_type,updated_at,created_at,tags,source_ref,org_type").eq("is_active",!0).contains("source_ref",{source:"hubspot"}).order("updated_at",{ascending:!1}).limit(Er);if(E)throw E;return D||[]},refetchOnWindowFocus:!1,retry:!1});i.useEffect(()=>{T&&(W("HubSpotLibrary",T,"Failed to load HubSpot library:"),I({title:"Failed to load items",description:"Could not load HubSpot records",variant:"destructive"}))},[T,I]),i.useEffect(()=>{p(D=>{const E=new Set(k.map(L=>L.id)),N=new Set([...D].filter(L=>E.has(L)));return N.size===D.size?D:N})},[k]);const w=D=>{p(E=>{const N=new Set(E);return N.has(D)?N.delete(D):N.add(D),N})},b=()=>{f.size===k.length?p(new Set):p(new Set(k.map(D=>D.id)))},P=()=>{p(new Set)},l=k.length>0&&f.size===k.length,$=f.size>0,Q=async D=>{if(confirm("Are you sure you want to remove this item from your library? This will delete the document and cannot be undone.")){m(D);try{await Ms({doc_id:D}),await O(),p(E=>{const N=new Set(E);return N.delete(D),N})}catch(E){W("HubSpotLibrary",E,"Failed to delete document:");const N=E instanceof Error?E.message:"Unknown error";I({title:"Failed to remove item",description:N||"Could not remove the item",variant:"destructive"})}finally{m(null)}}},re=async()=>{const D=f.size;if(D!==0&&confirm(`Are you sure you want to remove ${D} item${D>1?"s":""} from your library? This will delete the documents and cannot be undone.`)){y(!0);try{const E=Array.from(f);let N=0,L=0;for(const U of E)try{await Ms({doc_id:U}),N++}catch(Z){W("HubSpotLibrary",Z,`Failed to delete document ${U}:`),L++}I(L===0?{title:"Items removed",description:`Successfully removed ${N} item${N>1?"s":""} from your library`,variant:"success"}:{title:"Partial success",description:`Removed ${N} item${N>1?"s":""}, ${L} failed`,variant:"destructive"}),await O(),p(new Set)}catch(E){W("HubSpotLibrary",E,"Failed to bulk delete documents:");const N=E instanceof Error?E.message:"Unknown error";I({title:"Failed to remove items",description:N||"Could not remove the items",variant:"destructive"})}finally{y(!1)}}};if(S)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(it,{className:"h-6 w-6 animate-spin",style:{color:"var(--text-bright)"}})});if(!k.length)return e.jsx(xn,{connected:!0,selectionCount:s,selectionNames:r,lastSync:n,scopeSavedAt:a,selectionNoun:o,isSyncing:d,progress:g,lastSyncOutcome:c,onOpenScope:u,onSyncNow:h});const K=gn(k.length,t);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsxs("div",{className:"dialog-list-toolbar",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Vt,{checked:l?!0:$?"indeterminate":!1,onCheckedChange:b,"aria-label":l?"Deselect all":"Select all",className:"cursor-pointer"}),e.jsx("span",{className:"text-sm",style:{color:"var(--text-primary)"},children:$?e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--text-bright)"},children:f.size})," ","of ",k.length," selected"]}):e.jsxs(e.Fragment,{children:[k.length," record",k.length!==1?"s":""]})}),K&&e.jsx("span",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:K})]}),$&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(q,{variant:"ghost",size:"sm",onClick:P,disabled:v,className:"text-xs",children:"Clear"}),e.jsx(q,{variant:"destructive",size:"sm",onClick:()=>void re(),className:"text-xs",loading:v,children:v?"Removing...":e.jsxs(e.Fragment,{children:[e.jsx(Ns,{className:"h-3.5 w-3.5"}),"Remove ",f.size," record",f.size>1?"s":""]})})]})]}),e.jsx("div",{className:"dialog-list-container",children:k.map(D=>{var L,U;const E=f.has(D.id),N=((L=D.source_ref)==null?void 0:L.object_type)||"unknown";return e.jsxs("div",{className:`dialog-list-row ${E?"selected":""}`,children:[e.jsx(Vt,{checked:E,onCheckedChange:()=>w(D.id),"aria-label":`Select ${D.title}`,className:"cursor-pointer shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0 overflow-hidden",children:[e.jsx("div",{className:"dialog-list-row-title",title:D.title,children:D.title}),e.jsxs("div",{className:"dialog-list-row-meta",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium mr-2",style:{backgroundColor:"rgba(255, 122, 89, 0.15)",color:"#FF7A59"},children:[km[N],Cm[N]||N]}),os(D.updated_at||D.created_at,"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"dialog-list-row-actions",children:[((U=D.source_ref)==null?void 0:U.url)&&e.jsxs("a",{href:D.source_ref.url,target:"_blank",rel:"noopener noreferrer",className:"dialog-external-link",children:[e.jsx(jr,{className:"h-3.5 w-3.5 shrink-0"}),"View in HubSpot"]}),e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsx(q,{variant:"destructive",size:"icon-sm",onClick:()=>void Q(D.id),disabled:v,loading:x===D.id,"aria-label":"Remove",children:e.jsx(Ns,{className:"h-4 w-4"})})}),e.jsx(Ct,{children:"Remove"})]})]})]},D.id)})})]})}const ea=["google","dropbox","trello","notion","slack","hubspot","webhook","email"];function ta(t,s){return s===vt.ERROR?"error":s===vt.REAUTH_REQUIRED||s===vt.DISABLED?"warning":"success"}const mi="MMM d, yyyy 'at' h:mm a";function Im(t){if(!t)return;const s=os(t,mi,"");if(s)return`Last synced ${s}`}function Tm(t){var r,n;if(!t)return!1;
8const s=(n=(r=t.syncConfig)==null?void 0:r.hubspot)==null?void 0:n.object_types;return Array.isArray(s)&&s.length>0}const Dm={google:"folder",dropbox:"folder",trello:"board",hubspot:"record type",notion:"page"};function Rm(t,s){var r,n,a,o,d,g;if(s){if(t==="google"){const c=(n=(r=s.syncConfig)==null?void 0:r.google)==null?void 0:n.selections;return Array.isArray(c)?c.map(u=>u.name).filter(Boolean):void 0}if(t==="dropbox"){const c=(o=(a=s.syncConfig)==null?void 0:a.dropbox)==null?void 0:o.folders;return Array.isArray(c)?c.map(u=>u.split("/").filter(Boolean).pop()??u):void 0}if(t==="hubspot"){const c=(g=(d=s.syncConfig)==null?void 0:d.hubspot)==null?void 0:g.object_types;return Array.isArray(c)?c:void 0}}}function Am({googleConn:t,trelloConn:s,slackConn:r,notionConn:n,dropboxConn:a,hubspotConn:o,webhookConnections:d,libraryCounts:g,isGoogleSyncing:c,isTrelloSyncing:u,isNotionSyncing:h,isDropboxSyncing:x,isHubSpotSyncing:m,googleSyncProgress:f,integrationSyncProgress:p,googleSyncOutcome:v=null,integrationSyncOutcome:y=null,autoSyncPending:I,onAutoSyncChange:M,onDisconnect:k,onGoogleSync:S,onIntegrationSync:T,onOpenWebhookSetup:O,onOpenWebhookSettings:w,onSlackDisconnect:b,isDisconnecting:P=!1,postConnectScope:l=null,onPostConnectScopeHandled:$,preferSaveAndSync:Q=!1,onScopeSaved:re}){var mt,et,Tt,Yt,ft;const{toast:K}=ze(),[D,E]=Es(),N=ct(),L=Ks(),{data:U,isLoading:Z,error:le}=Ul(),[De,fe]=i.useState(!1),[ye,pe]=i.useState("overview"),[de,F]=i.useState(0),[Y,ie]=i.useState(0),oe=i.useCallback(j=>ie(j.driveFiles),[]),C=wa.BROKER_EMAIL_CONNECT,A=!!U,B=!!(t!=null&&t.connected)&&(t==null?void 0:t.syncStatus)===vt.REAUTH_REQUIRED,te=!!(t!=null&&t.connected)&&au(t),he=!!(s!=null&&s.connected)&&Array.isArray((et=(mt=s.syncConfig)==null?void 0:mt.trello)==null?void 0:et.boards)&&(((ft=(Yt=(Tt=s.syncConfig)==null?void 0:Tt.trello)==null?void 0:Yt.boards)==null?void 0:ft.length)??0)>0,ue=!!(a!=null&&a.connected)&&ri(a),Ae=!!(o!=null&&o.connected)&&Tm(o),Ce=()=>{K({title:"Redirect blocked",description:"The redirect URL is not allowed.",variant:"destructive"})},xe=j=>{Rn(j).then(({url:ee})=>{ee&&Or(ee)?window.location.assign(ee):ee?Ce():K({title:"Connection failed",description:"No redirect URL was returned. Please try again.",variant:"destructive"})}).catch(ee=>{Je(K,ee,`connecting ${j}`)})},$e=async j=>{try{const ee=await To({provider:j,frontendUrl:window.location.origin});ee!=null&&ee.url&&Or(ee.url)?window.location.href=ee.url:ee!=null&&ee.url?Ce():K({title:"Connection failed",description:"No redirect URL was returned. Please try again.",variant:"destructive"})}catch(ee){Je(K,ee,`connecting ${j}`)}},se=()=>{fe(!0),Rn("google",cr.EMAIL).then(({url:j})=>{j&&Or(j)?window.location.href=j:j?(fe(!1),Ce()):(fe(!1),K({title:"Connection failed",description:"No redirect URL was returned. Please try again.",variant:"destructive"}))}).catch(j=>{fe(!1),Je(K,j,"starting the Gmail connection")})},ke=()=>{L.mutate({provider:"google",integrationType:cr.EMAIL})},Ee={google:!!(t!=null&&t.connected),trello:!!(s!=null&&s.connected),slack:!!(r!=null&&r.connected),notion:!!(n!=null&&n.connected),dropbox:!!(a!=null&&a.connected),hubspot:!!(o!=null&&o.connected),webhook:d.length>0,email:A},Xe={google:{title:"Google Drive",subtext:"Sync documents and files from your Drive",icon:e.jsx(Eo,{className:"h-4 w-4"}),lastSync:t==null?void 0:t.lastSync,syncStatus:t==null?void 0:t.syncStatus},dropbox:{title:"Dropbox",subtext:"Sync chosen folders into your knowledge base",icon:e.jsx(va,{className:"h-4 w-4"}),lastSync:a==null?void 0:a.lastSync,syncStatus:a==null?void 0:a.syncStatus},trello:{title:"Trello",subtext:"Sync boards and cards from Trello",icon:e.jsx(ya,{className:"h-4 w-4"}),lastSync:s==null?void 0:s.lastSync,syncStatus:s==null?void 0:s.syncStatus},notion:{title:"Notion",subtext:"Sync pages and databases you shared in Notion",icon:e.jsx(Co,{className:"h-4 w-4 text-white"}),lastSync:n==null?void 0:n.lastSync,syncStatus:n==null?void 0:n.syncStatus},slack:{title:"Slack",subtext:"Ask your knowledge base from Slack with /sa",icon:e.jsx(ko,{className:"h-4 w-4"}),lastSync:null,syncStatus:r==null?void 0:r.syncStatus},hubspot:{title:"HubSpot",subtext:"Sync contacts, companies, deals, and tickets",icon:e.jsx(ba,{className:"h-4 w-4"}),lastSync:o==null?void 0:o.lastSync,syncStatus:o==null?void 0:o.syncStatus},webhook:{title:"Custom Webhooks",subtext:"Push content from Zapier, n8n, and other tools",icon:e.jsx(No,{className:"h-4 w-4"}),lastSync:null}
8,email:{title:"Email",subtext:"Connect your inbox so your assistant can draft and send for you",icon:e.jsx(_a,{className:"h-4 w-4"}),lastSync:null,hidden:!C}},bt=(j,ee)=>{const me=Xe[j],Le=Im(me.lastSync),tt=ee?j==="email"&&(U!=null&&U.email)?U.email:Le:"Not connected";return{id:j,title:me.title,subtext:me.subtext,icon:me.icon,statusTone:ee?ta(!0,me.syncStatus??null):void 0,meta:tt,muted:!ee}},Qe=i.useMemo(()=>{const j=ea.filter(me=>!Xe[me].hidden&&Ee[me]),ee=ea.filter(me=>!Xe[me].hidden&&!Ee[me]);return[{label:"Connected",items:j.map(me=>bt(me,!0))},{label:"Available",items:ee.map(me=>bt(me,!1))}]},[t,s,r,n,a,o,d,U,C]),dt=i.useMemo(()=>Qe.flatMap(j=>j.items.map(ee=>ee.id)).filter(Boolean),[Qe]),Kt=D.get("connector"),pt=Kt&&dt.includes(Kt)?Kt:null,Ze=i.useCallback(j=>{E(ee=>{const me=new URLSearchParams(ee);return me.set("connector",j),me},{replace:!0}),pe("overview")},[E]);i.useEffect(()=>{var Le,tt,Lt,Ht;if(pt||dt.length===0)return;const j=(tt=(Le=Qe[0])==null?void 0:Le.items[0])==null?void 0:tt.id,ee=(Ht=(Lt=Qe[1])==null?void 0:Lt.items[0])==null?void 0:Ht.id,me=j??ee;me&&Ze(me)},[pt,dt,Qe,Ze]),i.useEffect(()=>{var j;if(l){if((j=Xe[l])!=null&&j.hidden){$==null||$();return}Ze(l),pe(l==="slack"||l==="email"?"overview":"scope"),$==null||$()}},[l]);const Ie=pt??dt[0]??null,ot=j=>{if(j==="email"||j==="slack")return[{id:"overview",label:"Overview",icon:e.jsx(Js,{className:"h-4 w-4"})}];if(j==="webhook")return[{id:"overview",label:"Overview",icon:e.jsx(Js,{className:"h-4 w-4"})},{id:"settings",label:"Settings",icon:e.jsx(Il,{className:"h-4 w-4"})}];if(j==="google")return[{id:"overview",label:"Library",icon:e.jsx(Js,{className:"h-4 w-4"})}];const ee=yu(j,{libraryCount:Ee[j]?g.get(j):void 0,scopeCount:zn(j,ut(j)),isSyncing:jt(j)});return[{id:"overview",label:ee.overview,icon:e.jsx(Js,{className:"h-4 w-4"})},{id:"scope",label:ee.scope,icon:e.jsx(ln,{className:"h-4 w-4"})}]},Be=()=>{F(j=>j+1)},Wt=()=>{N.invalidateQueries({queryKey:["connections"]})},wt=j=>{const ee=Ee[j];if(j==="email"){const tt=Z?"Checking your email connection…":le?"Couldn't load your email connection. Refresh to retry.":void 0;return ee?e.jsx(q,{variant:"outline",size:"sm",onClick:ke,disabled:Z||!!le,loading:L.isPending,disabledReason:tt,children:"Disconnect"}):e.jsx(q,{size:"sm",onClick:se,disabled:Z||!!le,loading:De,disabledReason:tt,children:"Connect"})}if(!ee)return e.jsx(q,{size:"sm",onClick:()=>{j==="google"||j==="trello"||j==="slack"?xe(j):j==="notion"||j==="dropbox"||j==="hubspot"?$e(j):j==="webhook"&&O()},children:"Connect"});if(j==="slack")return e.jsxs(q,{variant:"secondary",size:"sm",onClick:()=>pe("overview"),children:[e.jsx(Tl,{className:"h-3.5 w-3.5"}),"How to use"]});if(j==="webhook")return e.jsx(q,{size:"sm",onClick:O,children:"Add webhook"});if(j==="google")return B?e.jsxs(q,{size:"sm",onClick:()=>xe("google"),children:[e.jsx(Xr,{className:"h-3.5 w-3.5"}),"Reconnect"]}):te?e.jsxs(e.Fragment,{children:[e.jsxs(q,{size:"sm",onClick:Be,children:[e.jsx(_r,{className:"h-3.5 w-3.5","aria-hidden":!0}),"Add from Google Drive"]}),e.jsxs(q,{variant:"secondary",size:"sm",onClick:S,disabled:c,loading:c,disabledReason:c?"A sync is already running":void 0,children:[e.jsx(Zt,{className:"h-3.5 w-3.5"}),"Sync Now"]})]}):e.jsx(q,{size:"sm",onClick:()=>pe("scope"),children:"Finish setup"});const me=j==="trello"?he:j==="dropbox"?ue:j==="hubspot"?Ae:!0,Le=j==="trello"&&u||j==="notion"&&h||j==="dropbox"&&x||j==="hubspot"&&m;return me?e.jsxs(q,{size:"sm",onClick:()=>T(j),loading:Le,disabledReason:Le?"A sync is already running":void 0,children:[e.jsx(Zt,{className:"h-3.5 w-3.5"}),"Sync Now"]}):e.jsx(q,{size:"sm",onClick:()=>pe("scope"),children:"Finish setup"})},_t=j=>{var ee;return j==="email"?(U==null?void 0:U.email)??void 0:((ee=ut(j))==null?void 0:ee.email)??void 0},At=j=>{if(!Ee[j])return e.jsx(yt,{variant:"secondary",children:"Not connected"});const me=ta(!0,Xe[j].syncStatus??null);if(me==="error")return e.jsx(yt,{variant:"destructive",children:"Error"});if(me==="warning")return e.jsx(yt,{variant:"warning",children:"Needs attention"});const Le=_t(j);return e.jsx(yt,{variant:"success",children:Le?`Connected (${Le})`:"Connected"})}
8,gt=j=>j==="google"||j==="trello"||j==="notion"||j==="dropbox"||j==="hubspot"?j:null,xt=j=>j==="google"?{progress:f,outcome:v}:{progress:p,outcome:y},jt=j=>j==="google"&&c||j==="trello"&&u||j==="notion"&&h||j==="dropbox"&&x||j==="hubspot"&&m,ut=j=>{if(j==="google")return t;if(j==="trello")return s;if(j==="notion")return n;if(j==="dropbox")return a;if(j==="hubspot")return o;if(j==="slack")return r},Pt=j=>{if(j==="slack"){b();return}if(j==="email"){ke();return}(j==="google"||j==="trello"||j==="dropbox"||j==="hubspot"||j==="notion")&&k(j)},It=j=>{var me;if(!Ee[j]||j==="email"||j==="webhook")return null;const ee=P||L.isPending;return e.jsxs(ir,{children:[e.jsx(or,{asChild:!0,children:e.jsx(q,{variant:"ghost",size:"icon",loading:ee,"aria-label":"More connector actions",className:"text-soft-muted hover:text-soft-bright",children:e.jsx(mr,{className:"h-4 w-4","aria-hidden":!0})})}),e.jsxs(lr,{align:"end",children:[gt(j)&&e.jsxs(e.Fragment,{children:[e.jsx(Io,{checked:((me=ut(j))==null?void 0:me.autoSync)??!1,onCheckedChange:Le=>{const tt=gt(j);tt&&M(tt,Le)},disabled:I,"aria-label":"Weekly auto-sync",onSelect:Le=>Le.preventDefault(),children:"Weekly auto-sync"}),e.jsx(ga,{})]}),e.jsx(Mt,{onSelect:()=>Pt(j),disabled:ee,children:"Disconnect"})]})]})},G=j=>{var Le,tt,Lt,Ht;const ee=Ee[j];if(j==="email")return e.jsxs("div",{className:"space-y-3 text-sm",style:{color:"var(--platform-text-secondary)"},children:[e.jsx("p",{children:"Lets the assistant write email drafts in your Gmail for you to review. Drafts are never sent. This is a separate sign-in from Google Drive."}),A&&(U!=null&&U.email)?e.jsxs("p",{style:{color:"var(--platform-text-primary)"},children:["Connected as ",U.email]}):null]});if(j==="slack")return e.jsxs("div",{className:"space-y-3 text-sm",style:{color:"var(--platform-text-secondary)"},children:[e.jsxs("p",{children:["In any Slack channel where the Simply Asking app is installed, type"," ",e.jsx("code",{className:"text-soft-bright",children:"/sa"})," followed by your question."]}),e.jsx("p",{children:"Answers come from your connected knowledge base with the same grounding rules as Ask. Slack does not sync channel messages into your knowledge base."})]});if(j==="webhook")return e.jsxs("div",{className:"space-y-4 text-sm",style:{color:"var(--platform-text-secondary)"},children:[e.jsx("p",{children:"Create a webhook endpoint to push documents from Zapier, n8n, or custom scripts into your knowledge base."}),d.length>0&&e.jsx("ul",{className:"space-y-2",children:d.map(es=>e.jsxs("li",{className:"glass-inset flex items-center justify-between gap-2 rounded-2xl px-3 py-2",children:[e.jsx("span",{style:{color:"var(--platform-text-primary)"},children:es.displayName||"Webhook"}),e.jsx(q,{variant:"ghost",size:"sm",onClick:()=>w==null?void 0:w(es),children:"Manage"})]},es.id))}),d[0]&&e.jsx(Kl,{title:"Library",children:e.jsx(Vu,{connectionId:d[0].id,connectionName:d[0].displayName||"Webhook"})})]});if(j==="notion")return e.jsxs("div",{className:"space-y-4 text-sm",style:{color:"var(--platform-text-secondary)"},children:[e.jsx("p",{children:"Simply Asking syncs pages and databases you shared during Notion authorization. To change which pages are available, disconnect and reconnect, then share the pages you want in Notion's permission screen."}),ee&&e.jsx("p",{className:"text-xs border-t border-[var(--white-10)] pt-3",children:"Synced content appears in Library after each successful sync."})]});const me={totalCount:g.get(j)??null,selectionCount:zn(j,ut(j)),selectionNames:Rm(j,ut(j)),lastSync:Xe[j].lastSync??null,scopeSavedAt:j==="google"?((tt=(Le=t==null?void 0:t.syncConfig)==null?void 0:Le.google)==null?void 0:tt.scope_saved_at)??(t==null?void 0:t.updatedAt)??null:((Lt=ut(j))==null?void 0:Lt.updatedAt)??null,selectionNoun:Dm[j],isSyncing:jt(j),progress:xt(j).progress,lastSyncOutcome:xt(j).outcome,libraryRefreshKey:((Ht=xt(j).outcome)==null?void 0:Ht.batchId)??null,onOpenScope:()=>pe("scope"),onSyncNow:()=>j==="google"?S():T(j)};return e.jsxs("div",{className:"space-y-4 text-sm",style:{color:"var(--platform-text-secondary)"},children:[ee&&j==="google"&&e.jsxs(e.Fragment,{children:[e.jsx(xm,{variant:"inline",connection:t,onAddFromDrive:Be,onRowsSummary:oe,...me}),e.jsx(Ju,{variant:"picker-only",open:!0,onOpenChange:()=>{},connection:t,onDisconnect:()=>k("google"),isDisconnecting:P,onSaved:Wt,pickerOpenSignal:de})]}),ee&&j==="trello"&&e.jsx(wm,{...me}),ee&&j==="hubspot"&&e.jsx(Em,{...me}),ee&&j==="dropbox"&&e.jsx("p",{className:"text-xs border-t border-[var(--white-10)] pt-3",children:"Synced content appears in Library after each successful sync."})]})},ne=j=>{if(!Ee[j])return e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-muted)"},children:"Connect this app first, then choose what to sync here."});const ee=()=>
8{re==null||re(j),pe("overview")};return j==="google"?G("google"):j==="trello"?e.jsx(vm,{variant:"inline",open:!0,onOpenChange:()=>{},connection:s,preferSaveAndSync:Q,onSave:ee}):j==="dropbox"?e.jsx(jm,{variant:"inline",open:!0,onOpenChange:()=>{},connection:a,preferSaveAndSync:Q,onSave:ee}):j==="hubspot"?e.jsx(Sm,{variant:"inline",open:!0,onOpenChange:()=>{},connection:o,preferSaveAndSync:Q,onSave:ee}):j==="notion"?e.jsx("div",{className:"space-y-3 text-sm",style:{color:"var(--platform-text-secondary)"},children:e.jsx("p",{children:"Scope is chosen during Notion authorization. Disconnect and reconnect to change which pages are shared."})}):null},ce=j=>j!=="webhook"?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-secondary)"},children:"Manage webhook endpoints, rotate secrets, and review IP allowlists."}),e.jsx(q,{size:"sm",onClick:O,children:"Add webhook"}),d[0]&&e.jsx(q,{variant:"secondary",size:"sm",onClick:()=>w==null?void 0:w(d[0]),children:"Open settings"})]});if(!Ie)return e.jsx(Pn,{sections:Qe,selectedId:null,onSelect:Ze,directoryAriaLabel:"Integrations",density:"comfortable",desktopRailTestId:"connector-rail-desktop",resizable:!0,resizeStorageKey:"add-sync",children:null});const J=Xe[Ie],ve=(()=>{const j=[`${Y} file${Y===1?"":"s"} from Drive`],ee=g.get("google");!jt("google")&&typeof ee=="number"&&j.push(`${ee} in your library`);const me=os(t==null?void 0:t.lastSync,mi,"");return j.push(me?`last synced ${me}`:"not synced yet"),j.join(" · ")})(),Pe=ot(Ie),qe=Pe.some(j=>j.id===ye)?ye:"overview";return e.jsx(Pn,{sections:Qe,selectedId:Ie,onSelect:Ze,directoryAriaLabel:"Integrations",density:"comfortable",desktopRailTestId:"connector-rail-desktop",resizable:!0,resizeStorageKey:"add-sync",children:e.jsxs("div",{className:"flex flex-col gap-5 min-h-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl",style:{background:"var(--gold-12)",border:"1px solid var(--glass-inset-border)"},children:J.icon}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold truncate",style:{color:"var(--platform-text-primary)"},children:J.title}),At(Ie)]}),hn(Ie)&&e.jsx("div",{className:"flex flex-wrap items-center gap-x-2",children:Ie==="google"&&Ee.google?e.jsx("p",{className:"mt-1.5 text-xs",style:{color:"var(--platform-text-muted)"},"data-testid":"drive-header-sentence",children:ve}):e.jsx(Nu,{connected:Ee[Ie],syncStatus:J.syncStatus,lastSync:J.lastSync,libraryCount:jt(Ie)?null:g.get(Ie)??null})})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-nowrap items-center justify-end gap-2",children:[wt(Ie),It(Ie)]})]}),Pe.length>1&&e.jsx(Wl,{tabs:Pe.map(j=>({value:j.id,label:j.label,icon:j.icon})),value:qe,onChange:j=>pe(j),ariaLabel:`${J.title} sections`}),e.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto",children:[qe==="overview"&&G(Ie),qe==="scope"&&ne(Ie),qe==="settings"&&ce(Ie)]})]})})}function fi({embedded:t=!1}={}){wr(t?"Add":"Integrations");const{toast:s}=ze(),{orgId:r,role:n}=Ve(),{count:a}=Gl(),o=a,d=Gs(n),g=ct(),[c,u]=Es(),h=i.useRef(!1),x=i.useRef(!1),{data:m,isLoading:f,error:p}=Ua(),v=dn(),y=Ks(),I=Ma(),{data:M=[],isLoading:k,error:S}=Bl(),T=M,O=zl(),w=du(m),[b,P]=i.useState(new Map),[l,$]=i.useState(null),[Q,re]=i.useState(null),[K,D]=i.useState(!1),[E,N]=i.useState(!1),[L,U]=i.useState(null),[Z,le]=i.useState(!1),[De,fe]=i.useState(null),{data:ye=[],isLoading:pe,error:de}=Ya(),{currentBatchId:F,setCurrentBatchId:Y,syncProgress:ie,setSyncProgress:oe,syncStartTime:C,setSyncStartTime:A,integrationBatchId:B,setIntegrationBatchId:te,syncingIntegration:he,setSyncingIntegration:ue,integrationSyncStartTime:Ae,setIntegrationSyncStartTime:Ce}=ud({activeSyncBatches:ye,isRunSyncPending:v.isPending}),xe=en(F),$e=en(B),se=m==null?void 0:m.find(G=>G.provider==="google"),ke=m==null?void 0:m.find(G=>G.provider==="trello"),Ee=m==null?void 0:m.find(G=>G.provider==="slack"),Xe=m==null?void 0:m.find(G=>G.provider==="notion"),bt=m==null?void 0:m.find(G=>G.provider==="dropbox"),Qe=m==null?void 0:m.find(G=>G.provider==="hubspot"),dt=(m??[]).filter(G=>G.provider==="webhook").map(G=>{const ne=G;return{id:ne.id||"",provider:"webhook",connected:!0,displayName:ne.display_name||ne.displayName||void 0,customIcon:ne.display_icon_url||void 0,webhookUrl:"/functions/v1/webhook-ingest",documentCount:ne.total_documents_synced||0,lastWebhookAt:ne.last_webhook_at||null,email:null}});i.useEffect(()=>{const G=c.get("setup");if(!G||x.current||f||!m)return;x.current=!0,h.current=!0,le(!0);const ne=c.get("kind"),ce=()=>{const J=new URLSearchParams(c);J.delete("setup"),J.delete("success"),J.delete("kind"),u(J,{replace:!0})};switch(G){case"google":{if(ne===cr.EMAIL){h.current=!1,fe("email"),s({title:"Gmail connected",description:"The assistant can now write email drafts for you to review. Drafts are never sent.",variant:"success"});break}const J=m.find(ve=>ve.provider==="google");J!=null&&J.connected&&(le(!0),fe("google"));break}case"trello":m.some(J=>J.provider==="trello"&&J.connected)&&(le(!0),fe("trello"));break;
8case"hubspot":m.some(J=>J.provider==="hubspot"&&J.connected)&&(le(!0),fe("hubspot"));break;case"dropbox":m.some(J=>J.provider==="dropbox"&&J.connected)&&(le(!0),fe("dropbox"));break;case"notion":m.some(J=>J.provider==="notion"&&J.connected)&&(fe("notion"),h.current=!1);break;case"slack":m.some(J=>J.provider==="slack"&&J.connected)&&(fe("slack"),h.current=!1,s({title:"Slack connected",description:"Ask your knowledge base in Slack with /sa.",variant:"success"}));break;default:h.current=!1;break}ce()},[c,u,m,f,s]),i.useEffect(()=>{T.length>0&&!v.isPending&&T.some(ne=>{var ve,Pe;const ce=ne.processed!==null&&ne.processed!==void 0,J=((ve=ne.note)==null?void 0:ve.includes("Sync failed:"))||((Pe=ne.note)==null?void 0:Pe.includes("Errors:"));return ce||J})&&g.invalidateQueries({queryKey:["connections"]})},[T,g,v.isPending]),i.useEffect(()=>{if(v.isPending){const G=setInterval(()=>{g.invalidateQueries({queryKey:["recent-syncs"]})},2e3);return()=>clearInterval(G)}},[v.isPending,g]),i.useEffect(()=>{if(xe!=null&&xe.data&&F){const G=xe.data,ne=G.completed+G.skipped+G.failed,ce=G.total;oe({current:ne,total:ce,fileName:G.currentFileName}),ne>=ce&&G.pending===0&&G.processing===0&&(oe({current:ce,total:ce,fileName:void 0}),(l==null?void 0:l.batchId)!==F&&($({batchId:F,completed:G.completed,failed:G.failed,skipped:G.skipped,total:ce}),g.invalidateQueries({queryKey:["connections"]}),g.invalidateQueries({queryKey:["recent-syncs"]}),G.failed>0&&s({title:"Some items didn't sync",description:`Brought in ${G.completed} · couldn't bring in ${G.failed}. Try syncing again.`,variant:"warning"})),setTimeout(()=>{oe(null),A(null),Y(null),g.invalidateQueries({queryKey:["connections"]}),g.invalidateQueries({queryKey:["recent-syncs"]})},3e3))}else!v.isPending&&!F&&(oe(null),A(null))},[xe==null?void 0:xe.data,F,v.isPending,g,s,l==null?void 0:l.batchId,oe,A,Y]),i.useEffect(()=>{if(B){const G=setInterval(()=>{g.invalidateQueries({queryKey:["sync-staging",B]})},2e3);return()=>clearInterval(G)}},[B,g]),i.useEffect(()=>{if($e!=null&&$e.data&&B){const G=$e.data,ne=G.completed+G.skipped+G.failed,ce=G.total;if(ne>=ce&&G.pending===0&&G.processing===0){const J=G.completed,ve=G.skipped,Pe=G.failed;(Q==null?void 0:Q.batchId)!==B&&(re({batchId:B,completed:J,failed:Pe,skipped:ve,total:ce}),g.invalidateQueries({queryKey:["connections"]})),s({...$c({syncedCount:J,skippedCount:ve,errorCount:Pe,total:ce,awaitingReviewCount:o}),action:o>0?e.jsx(Mc,{}):void 0}),setTimeout(()=>{ue(null),te(null),Ce(null),P(qe=>{const mt=new Map(qe);return mt.delete(B),mt}),g.invalidateQueries({queryKey:["connections"]}),g.invalidateQueries({queryKey:["recent-syncs"]})},1e3)}}},[$e==null?void 0:$e.data,B,Q==null?void 0:Q.batchId,o,g,s,ue,te,Ce]),i.useEffect(()=>{if(!Ae||!he)return;const ne=1200*1e3-(Date.now()-Ae),ce=()=>{s({title:"Sync may still be processing",description:"The sync is taking longer than expected. Check your library for synced documents.",variant:"warning"}),ue(null),te(null),Ce(null),g.invalidateQueries({queryKey:["connections"]}),g.invalidateQueries({queryKey:["recent-syncs"]})};if(ne<=0){ce();return}const J=setTimeout(ce,ne);return()=>clearTimeout(J)},[Ae,he,g,s,ue,te,Ce]),Zc(m==null?void 0:m.length);const Kt=()=>se?!1:(s(xd(f)),!0),pt=()=>{Kt()||(A(Date.now()),oe({current:0,total:0}),Y(null),$(null),v.mutate({provider:"google",orgId:r,departmentId:null},{onSuccess:G=>{const ne=G;ne!=null&&ne.batchId&&(ne.queued??0)>0?(Y(ne.batchId),g.invalidateQueries({queryKey:["sync-staging",ne.batchId]})):(oe(null),A(null))}}))},Ze=()=>{pt()},Ie=G=>{if(g.invalidateQueries({queryKey:["connections"]}),!(!h.current&&!Z)){if(h.current=!1,le(!1),G==="google"){Ze();return}ot(G)}},ot=async G=>{var ne,ce;if(G==="trello"){const J=(ce=(ne=ke==null?void 0:ke.syncConfig)==null?void 0:ne.trello)==null?void 0:ce.boards;if(!Array.isArray(J)||J.length===0){s(Bn("trello")),le(!0),fe("trello");return}}if(G==="dropbox"&&(!bt||!ri(bt))){s(Bn("dropbox")),le(!0),fe("dropbox");return}ue(G),te(null),Ce(Date.now()),re(null);try{const J=await Ro({integrationId:G}),ve=J==null?void 0:J.batchId;ve?(te(ve),P(Pe=>new Map(Pe).set(ve,G)),g.invalidateQueries({queryKey:["sync-staging",ve]}),J.queued===0&&(s({title:"Everything is already synced",description:J.message||`All ${J.total||0} documents were already in your library.`,variant:"success"}),ue(null),te(null),P(Pe=>{const qe=new Map(Pe);return qe.delete(ve),qe}))):(s({title:"Sync started",description:`Processing documents from ${G}...`}),ue(null))}catch(J){W("Integrations",J,"Integration sync error:");const ve=J instanceof Error?J.message:"Unknown error";s({title:"Sync failed",description:ve||`Could not sync ${G}`,variant:"destructive"}),B||ue(null)}},Be=async(G,ne)=>{if(!v.isPending)try{if(ne){const{data:ce,error:J}=await X.from("sync_staging").select("id, retry_count").eq("sync_batch_id",ne).eq("status",Se.FAILED);if(J)throw new Error(`Failed to fetch failed records: ${J.message}`);
8if(!ce||ce.length===0){s({title:"No failed records",description:"There are no failed records to retry for this batch.",variant:"warning"});return}for(const ve of ce){const{error:Pe}=await X.from("sync_staging").update({status:Se.PENDING,error_message:null,retry_count:(ve.retry_count||0)+1,updated_at:new Date().toISOString()}).eq("id",ve.id);if(Pe)throw new Error(`Failed to reset record ${ve.id}: ${Pe.message}`)}Y(ne),A(Date.now()),oe({current:0,total:0}),g.invalidateQueries({queryKey:["sync-staging",ne]}),g.invalidateQueries({queryKey:["recent-syncs"]})}else{const ce=G.jobname.includes("drive")?"google":null;if(ce){A(Date.now()),oe({current:0,total:0}),Y(null);const ve=await v.mutateAsync({provider:ce,orgId:r,departmentId:null});ve!=null&&ve.batchId&&(Y(ve.batchId),g.invalidateQueries({queryKey:["sync-staging",ve.batchId]}))}}}catch(ce){W("Integrations",ce,"Retry sync error:");const J=ce instanceof Error?ce.message:"Unknown error";s({title:"Retry failed",description:J||"Could not retry sync",variant:"destructive"}),oe(null),A(null)}},Wt=async(G,ne)=>{var ve;const ce=(ve=G.note)==null?void 0:ve.match(/batch: ([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/i),J=ce?ce[1]:null;if(J)try{await X.from("sync_staging").update({status:Se.FAILED,error_message:"Cancelled by user",updated_at:new Date().toISOString()}).eq("sync_batch_id",J).in("status",[Se.PENDING,Se.PROCESSING])}catch(Pe){W("Integrations",Pe,"Error cancelling processing records:")}O.mutate(ne)};if(f)return e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(it,{className:"h-8 w-8 animate-spin text-primary"})});if(p)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 gap-2",children:[e.jsx(gs,{className:"h-8 w-8",style:{color:"var(--color-error, #ef4444)"}}),e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-secondary, rgba(255,255,255,0.7))"},children:"Failed to load integrations"})]});const wt=G=>he===G||B!==null&&b.get(B)===G,_t=v.isPending||F!==null,At=wt("trello"),gt=wt("notion"),xt=wt("dropbox"),jt=wt("hubspot"),ut=At||gt||xt||jt,{googleSyncProgress:Pt,integrationSyncProgress:It}=gd({isGoogleSyncing:_t,isIntegrationSyncing:ut,googleStaging:xe==null?void 0:xe.data,integrationStaging:$e==null?void 0:$e.data,googleFallback:ie,googleSyncStartTime:C,integrationSyncStartTime:Ae});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:t?"w-full":Ue(An.mainContent,An.sidebarPageGlow,Ut.platformPage),children:e.jsx("div",{className:t?"w-full":"w-full px-[60px] py-[40px]",children:e.jsxs("div",{className:"flex flex-col gap-8",children:[!t&&e.jsx(rn,{title:"Integrations",subtitle:"Connect and sync your external knowledge sources",helpHref:"/support/integrations",rightContent:e.jsx(q,{variant:"secondary",size:"sm",asChild:!0,children:e.jsxs("a",{href:Do,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(_a,{className:"h-4 w-4"}),"Install Browser Extension"]})})}),!t&&e.jsx("div",{className:"border-t border-[var(--gold-border)]"}),e.jsxs("div",{className:"space-y-[var(--spacing-2xl)]",children:[e.jsx(Am,{googleConn:se,trelloConn:ke,slackConn:Ee,notionConn:Xe,dropboxConn:bt,hubspotConn:Qe,webhookConnections:dt,libraryCounts:w,isGoogleSyncing:_t,isTrelloSyncing:At,isNotionSyncing:gt,isDropboxSyncing:xt,isHubSpotSyncing:jt,googleSyncProgress:Pt,integrationSyncProgress:It,googleSyncOutcome:l,integrationSyncOutcome:Q,autoSyncPending:I.isPending,onAutoSyncChange:(G,ne)=>I.mutate({provider:G,enabled:ne}),onDisconnect:G=>y.mutate(G==="google"?{provider:G,integrationType:cr.STORAGE}:G),onGoogleSync:()=>void Ze(),onIntegrationSync:G=>void ot(G),onOpenWebhookSetup:()=>D(!0),onOpenWebhookSettings:G=>{U(G),N(!0)},onSlackDisconnect:()=>{y.mutateAsync("slack")},isDisconnecting:y.isPending,postConnectScope:De,onPostConnectScopeHandled:()=>fe(null),preferSaveAndSync:Z,onScopeSaved:G=>{le(!1),hn(G)&&Ie(G)}}),!t&&e.jsx(su,{syncs:T,onRetry:(G,ne)=>void Be(G,ne),onDelete:(G,ne)=>void Wt(G,ne),runSyncPending:v.isPending}),!t&&e.jsxs("p",{className:"text-sm text-soft-secondary",children:["Actions the assistant took for you now live on the"," ",e.jsx(zs,{to:qt.TASKS,className:"text-[var(--gold)] hover:underline",children:"Tasks page"}),"."]}),d&&e.jsx(Xc,{})]})]})})}),e.jsx(Mu,{open:K,onOpenChange:D,onComplete:()=>{D(!1),g.invalidateQueries({queryKey:["connections"]})},orgId:r||""}),L&&e.jsx(qu,{open:E,onOpenChange:G=>{N(G),G||U(null)},connectionId:L.id,webhookName:L.displayName||"Webhook",onSecretRegenerated:()=>{g.invalidateQueries({queryKey:["connections"]})}})]})}function hi({children:t}){const{canConnect:s,isLoading:r}=ja();return r?e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})}
8):s?e.jsx(e.Fragment,{children:t}):e.jsx(Ao,{})}const pi="sa:write-tab:last-department-id";function Pm(){try{return window.localStorage.getItem(pi)}catch{return null}}function Lm(t){try{window.localStorage.setItem(pi,t)}catch{}}function gi({open:t,actionLabel:s="Publish",onOpenChange:r,onConfirm:n}){var x;const{data:a}=un({includeSystem:!0,enabled:!0}),o=as.useMemo(()=>a??[],[a]),d=((x=o.find(m=>m.is_system&&m.name===Po.PENDING_REVIEW))==null?void 0:x.id)??null,[g,c]=as.useState(null),u=as.useRef(!1);as.useEffect(()=>{if(t&&!u.current){const m=Pm();c(m&&o.some(f=>f.id===m)?m:null)}u.current=t},[t,o]);const h=m=>{m&&Lm(m),n(m)};return e.jsxs(nt,{open:t,onOpenChange:r,tier:"form",title:"Where does this belong?",description:"Choose an access group or hold these files for review.",icon:e.jsx(cn,{className:"h-5 w-5"}),footer:e.jsxs("div",{className:"flex items-center justify-end gap-2 w-full",children:[e.jsx(Ye,{variant:"secondary",onClick:()=>h(d),children:"Hold for review"}),e.jsx(Ye,{onClick:()=>h(g),disabled:!g,children:s})]}),children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Held files stay out of chat and search until an admin assigns access."}),e.jsx(Nr,{value:g??void 0,onChange:c,placeholder:"Select access group"})]})}function xi({isBusinessOrg:t,departmentId:s=null,onPublish:r}){const[n,a]=i.useState(!1),o=i.useCallback(()=>{if(!t||s){r(s??void 0);return}a(!0)},[t,s,r]),d=i.useCallback(g=>{a(!1),r(g)},[r]);return{open:n,setOpen:a,requestPublish:o,confirmPublish:d}}const Fm=as.lazy(()=>Fo(()=>import("./index-R7rnvG6Y.js").then(t=>t.kb),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(t=>({default:t.DocumentPreview})));function yi(){return e.jsx(Yr,{isEmpty:!0,emptyIcon:ps,emptyTitle:"Preview not available",emptyDescription:"You can still upload this file.",children:null})}class Om extends as.Component{constructor(){super(...arguments);_n(this,"state",{failed:!1})}static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(){this.props.onError()}render(){return this.state.failed?e.jsx(yi,{}):this.props.children}}function $m({file:t,onClose:s}){const[r,n]=i.useState(),[a,o]=i.useState(!1),d=i.useCallback(()=>o(!0),[]);return i.useEffect(()=>{if(!a)try{const g=URL.createObjectURL(t);return n(g),()=>URL.revokeObjectURL(g)}catch{o(!0)}},[t,a]),e.jsxs(nt,{open:!0,onOpenChange:g=>{g||s()},tier:"detail",maxWidth:"2xl",title:"File preview",icon:e.jsx(Dl,{}),description:"Check your file before uploading.",children:[e.jsx("p",{className:"text-sm text-soft-secondary break-words",children:t.name}),a?e.jsx(yi,{}):r?e.jsx(Om,{onError:d,children:e.jsx(i.Suspense,{fallback:e.jsx(Yr,{isLoading:!0,skeletonCount:2,children:null}),children:e.jsx(Fm,{fileUrl:r,fileName:t.name,mimeType:t.type,localFile:!0,onError:d})})}):e.jsx(Yr,{isLoading:!0,skeletonCount:2,children:null})]})}function vi({file:t,compact:s=!1,iconFallback:r}){const[n,a]=i.useState(null);return i.useEffect(()=>{a(null)},[t]),e.jsxs(e.Fragment,{children:[e.jsx(Lo,{children:e.jsxs(Nt,{children:[e.jsx(kt,{asChild:!0,children:e.jsxs(q,{variant:"ghost",size:s?"icon-sm":"sm",type:"button","aria-label":`Preview ${t.name}`,onClick:()=>a(t),children:[r,!s&&e.jsx("span",{children:"Preview"})]})}),e.jsxs(Ct,{children:["Preview ",t.name]})]})}),n===t&&e.jsx($m,{file:t,onClose:()=>a(null)})]})}function Mm({files:t,onRemove:s,uploading:r,progress:n=[]}){const a=new Map,o=[];t.forEach((g,c)=>{const u=ms(g);if(!u){o.push(c);return}const h=a.get(u.root_id)??{name:u.root_name,entries:[]};h.entries.push(c),a.set(u.root_id,h)});const d=g=>{const c=t[g],{Icon:u,color:h}=Ca(c.name),x=n.find(m=>m.entryId===ns(c));return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2",children:[e.jsx(vi,{file:c,compact:!0,iconFallback:e.jsx(u,{size:16,style:{color:h},className:"shrink-0"})}),e.jsx("span",{className:"flex-1 min-w-0 text-sm truncate",title:$r(c),style:{color:"var(--platform-text-primary)"},children:$r(c)}),x&&e.jsx("span",{className:"text-xs shrink-0",role:"status",style:{color:"var(--platform-text-muted)"},children:x.status===zt.COMPLETED?"Uploaded · processing":x.status===zt.FAILED?x.skipped?"Skipped · already in Library or needs review":x.error||"Not uploaded":x.status===zt.UPLOADING?"Uploading":"Waiting"}),e.jsx("span",{className:"text-xs shrink-0",style:{color:"var(--platform-text-muted)"},children:Qr(c.size)}),e.jsx(q,{variant:"ghost",size:"icon-xs",disabled:r,onClick:()=>s(g),"aria-label":`Remove ${$r(c)}`,children:e.jsx(at,{size:14})})]},ns(c))};return e.jsxs("div",{className:"flex flex-col divide-y divide-white/[0.06]",children:[[...a].map(([g,c])=>e.jsxs("details",{open:!0,className:"group",children:[e.jsxs("summary",{className:"flex cursor-pointer items-center gap-2 px-4 py-3 text-sm list-none",style:{color:"var(--platform-text-primary)"},children:[e.jsx(Ts,{size:16,className:"group-open:rotate-90","aria-hidden":!0}),e.jsx(ln,{size:16,"aria-hidden":!0}),e.jsx("span",{className:"truncate",children:c.name}),e.jsxs("span",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:[c.entries.length," files"]})]}),e.jsx("div",{className:"pl-4 divide-y divide-white/[0.06]",children:c.entries.map(d)})]},g)),o.map(d)]})}const ks={initial:{opacity:0}
8,animate:{opacity:1,transition:{duration:.2,ease:"easeOut"}},exit:{opacity:0,transition:{duration:0}}};function Um({families:t,ungroupedCount:s,onConfirm:r,onDismiss:n}){const[a,o]=i.useState(()=>new Set(t.map((x,m)=>m))),[d,g]=i.useState(!1),c=x=>{o(m=>{const f=new Set(m);return f.has(x)?f.delete(x):f.add(x),f})},u=()=>{const x=t.filter((f,p)=>a.has(p)),m=t.filter((f,p)=>!a.has(p));r({confirmed:x,rejected:m})},h=t.reduce((x,m)=>x+m.files.length,0);return e.jsxs("div",{className:"animate-in fade-in slide-in-from-top-2 duration-200",style:{borderRadius:"0.75rem",backgroundColor:"rgba(197, 160, 90, 0.06)",border:"1px solid rgba(197, 160, 90, 0.20)",padding:"0.75rem 1rem",marginBottom:"0.75rem"},children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("div",{className:"flex items-center justify-center shrink-0 bg-gold-icon-bg-active",style:{width:28,height:28,borderRadius:"0.5rem"},children:e.jsx(Rl,{className:"h-3.5 w-3.5 text-gold-icon"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium",style:{color:"var(--platform-text-primary)"},children:[t.length===1?`Detected: ${t[0].label}`:`Detected ${t.length} document families`,e.jsxs("span",{className:"ml-1.5 text-xs font-normal",style:{color:"var(--platform-text-secondary)"},children:["(",h," files)"]})]}),e.jsx("p",{className:"text-xs mt-0.5",style:{color:"var(--platform-text-secondary)"},children:"These will skip duplicate detection between each other"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("button",{type:"button",onClick:()=>g(!d),className:"p-1 rounded transition-colors hover:bg-white/5","aria-label":d?"Hide details":"Show details",children:d?e.jsx(Pa,{className:"h-4 w-4",style:{color:"var(--platform-text-secondary)"}}):e.jsx(Vs,{className:"h-4 w-4",style:{color:"var(--platform-text-secondary)"}})}),e.jsx(q,{variant:"ghost",size:"icon-sm",onClick:n,"aria-label":"Dismiss family detection",children:e.jsx(at,{className:"h-4 w-4",style:{color:"var(--platform-text-muted)"}})}),e.jsxs(q,{variant:"primary",size:"sm",onClick:u,className:"gap-1.5",children:[e.jsx(fs,{className:"h-3.5 w-3.5"}),"Looks right"]})]})]}),d&&e.jsxs("div",{className:"mt-3 space-y-2",children:[t.map((x,m)=>e.jsxs("button",{type:"button",role:"checkbox","aria-checked":a.has(m),"aria-label":`${x.label}: ${x.files.length} files`,onClick:()=>c(m),className:Ue("w-full flex items-center gap-3 px-3 py-2 rounded-lg text-left transition-all",a.has(m)?"bg-white/5 border border-[rgba(197,160,90,0.25)]":"bg-transparent border border-transparent opacity-60"),children:[e.jsx("div",{className:"flex items-center justify-center shrink-0",style:{width:18,height:18,borderRadius:"0.25rem",border:a.has(m)?"1.5px solid var(--gold)":"1.5px solid rgba(255,255,255,0.2)",backgroundColor:a.has(m)?"rgba(197, 160, 90, 0.15)":"transparent"},children:a.has(m)&&e.jsx(fs,{className:"h-3 w-3",style:{color:"var(--gold)"}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium",style:{color:"var(--platform-text-primary)"},children:[x.label,x.docType&&e.jsx("span",{className:"ml-2 text-xs px-1.5 py-0.5 rounded",style:{backgroundColor:"rgba(197, 160, 90, 0.10)",color:"var(--gold)"},children:"Transactional"})]}),e.jsxs("p",{className:"text-xs",style:{color:"var(--platform-text-secondary)"},children:[x.files.length," files",x.prefixes.length>0&&e.jsxs("span",{children:[" ","from ",x.prefixes.slice(0,3).join(", "),x.prefixes.length>3&&` +${x.prefixes.length-3} more`]})]})]})]},x.pattern)),s>0&&e.jsxs("p",{className:"text-xs px-3 pt-1",style:{color:"var(--platform-text-muted)"},children:["+",s," other file",s!==1?"s":""," will upload normally"]})]})]})}const sa=["purchase_order","invoice","receipt","shipping_order","compliance_form"],Bm=["distribution_instructions","inspection_report","work_order"];function zm({selected:t,onSelect:s,suggestedType:r,customTypes:n}){const[a,o]=i.useState(!1),d=n&&n.length>0,g=d?n.map(u=>u.slug):a?[...sa,...Bm]:sa,c=d?new Map(n.map(u=>[u.slug,u.label])):null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mb-3",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-wider mr-0.5",style:{color:"rgba(255, 255, 255, 0.35)"},children:"Type:"}),e.jsx(ra,{label:"General",isSelected:t===null,onClick:()=>s(null)}),g.map(u=>e.jsx(ra,{label:(c==null?void 0:c.get(u))??ar[u]??u,isSelected:t===u,isSuggested:r===u&&t!==u,onClick:()=>s(u)},u)),!a&&!d&&e.jsx(q,{variant:"link",size:"sm",onClick:()=>o(!0),style:{color:"rgba(255, 255, 255, 0.4)"},"aria-label":"Show more document types",children:"More..."})]})}function ra({label:t,isSelected:s,isSuggested:r,onClick:n}){return e.jsxs("button",{type:"button",role:"radio","aria-checked":s,"aria-label":`Document type: ${t}${r?" (suggested)":""}`,onClick:n,className:Ue("px-2.5 py-1 text-[12px] font-medium rounded-md","border transition-all duration-150 cursor-pointer",s?"border-white/[0.15] bg-white/[0.12] text-white":Ue("bg-white/[0.05] text-white/60","hover:border-white/[0.15] hover:bg-white/[0.08] hover:text-white/80",r?"border-white/[0.12] text-white/50":"border-white/[0.06]")),children:[t,r&&e.jsx("span",{className:"ml-1 text-[10px] text-white/40",children:"suggested"})]})}function qm({selectedFiles:t,onRemoveFile:s,onReset:r,onNavigate:n,batchDetection:a,onFamilyConfirm:o,onFamilyDismiss:d,showPreferencesSaved:g,selectedDocType:c,onDocTypeSelect:u,suggestedType:h,customChipTypes:x,fileInputRef:m,isDragOver:f,title:p,onTitleChange:v,summary:y,onSummaryChange:I,departmentId:M,onDepartmentChange:k,orgType:S,isUploading:T,uploadProgress:O,uploadFileProgress:w,onUpload:b,uploadDisabled:P=!1}){const[l,$]=i.useState(!1),[Q,re]=i.useState(""),[K,D]=i.useState(!1),E=t.length,N=t.reduce((F,Y)=>F+Y.size,0),L=E===1,U=t.some(F=>!!ms(F)),Z=t.length>0&&t.every(F=>{var ie;const Y=((ie=F.name.split(".").pop())==null?void 0:ie.toLowerCase())||"";return pl.includes(Y)}),le=t[0],{Icon:De,color:fe}=le?Ca(le.name):{Icon:rr,color:"var(--gold)"},ye=S===Oe.BUSINESS||S===Oe.INTERNAL,pe=xi({isBusinessOrg:ye,departmentId:M,onPublish:F=>{P||T||(F!==void 0&&k(F),b(F))}}),de=T||P||L&&!p.trim();return t.length===0?e.jsxs("div",{className:Ue("flex flex-col items-center justify-center gap-3 py-12 px-6 rounded-2xl cursor-pointer transition-all duration-200",f?"border-2 border-dashed border-white/30 bg-white/[0.06]":"border-2 border-dashed border-white/[0.15]"),onClick:()=>{var F;return(F=m.current)==null?void 0:F.click()},role:"button",tabIndex:0,onKeyDown:F=>{var Y;(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),(Y=m.current)==null||Y.click())}
8,children:[e.jsx("div",{className:Ue("w-14 h-14 rounded-full flex items-center justify-center transition-colors",f?"":"bg-white/[0.08]"),children:e.jsx(Da,{size:28,style:{color:f?"var(--gold)":"rgba(255,255,255,0.5)"}})}),e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[e.jsx("span",{className:"text-[15px] font-medium",style:{color:"rgba(255,255,255,0.9)"},children:f?"Release to upload":"Drop files here"}),e.jsx("span",{className:"text-[13px]",style:{color:"rgba(255,255,255,0.45)"},children:"or click to browse"})]}),e.jsx("div",{className:"text-[11px]",style:{color:"rgba(255,255,255,0.35)"},children:"20+ file types supported, up to 50MB"})]}):e.jsxs(is.div,{variants:ks,initial:"initial",animate:"animate",exit:"exit",className:"flex flex-col gap-4",children:[L&&!U&&le&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vi,{file:le,iconFallback:e.jsx(De,{size:20,style:{color:fe}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium truncate",style:{color:"var(--platform-text-primary)"},children:le.name}),e.jsxs("div",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:[Qr(le.size)," ·"," ",gl(le.name)]})]}),e.jsx(q,{variant:"ghost",size:"icon-sm",onClick:r,"aria-label":"Remove file",children:e.jsx(at,{size:16})})]}),(!L||U)&&e.jsxs("div",{className:"rounded-xl overflow-hidden",style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.1)"},children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-6 h-6",children:[e.jsx(rr,{size:16,style:{color:"rgba(255,255,255,0.6)"}}),e.jsx(rr,{size:16,className:"absolute top-0.5 left-0.5",style:{color:"rgba(255,255,255,0.3)"}})]}),e.jsxs("span",{className:"text-sm font-medium",style:{color:"rgba(255,255,255,0.9)"},children:[E," files selected"]})]}),e.jsxs("span",{className:"text-xs",style:{color:"rgba(255,255,255,0.5)"},children:[Qr(N)," total"]})]}),e.jsx(Mm,{files:t,onRemove:s,uploading:T,progress:w}),e.jsx("div",{className:"px-4 py-2 border-t border-white/[0.06]",children:e.jsx(q,{variant:"link",size:"sm",onClick:r,className:"text-xs",children:"Clear all"})})]}),a&&a.families.length>0&&e.jsx(Um,{families:a.families,ungroupedCount:a.ungrouped.length,onConfirm:o,onDismiss:d}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Title"}),l?e.jsx("input",{className:"dialog-input text-sm",value:p,onChange:F=>v(F.target.value),onBlur:()=>$(!1),onKeyDown:F=>{F.key==="Enter"&&$(!1),F.key==="Escape"&&(v(Q),$(!1))},autoFocus:!0,"aria-label":"Document title"}):e.jsxs("button",{className:"flex items-center gap-2 text-left w-full group dialog-input",onClick:()=>{re(p),$(!0)},style:{cursor:"text"},children:[e.jsx(ps,{size:15,className:"flex-shrink-0",style:{color:"var(--platform-text-muted)"}}),e.jsx("span",{className:"text-sm flex-1 truncate",style:{color:"var(--platform-text-primary)"},children:p||(L?"Untitled":"Titles auto-generated from filenames")}),e.jsx(Us,{size:13,className:"opacity-0 group-hover:opacity-40 transition-opacity flex-shrink-0",style:{color:"var(--platform-text-muted)"}})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Type"}),K?e.jsx(zm,{selected:c,onSelect:F=>{u(F),D(!1)},suggestedType:h,customTypes:x}):e.jsxs("button",{className:"dialog-input text-sm text-left flex items-center gap-2 group",onClick:()=>D(!0),style:{cursor:"pointer"},children:[e.jsx("span",{style:{color:"var(--platform-text-primary)"},children:c?ar[c]||c:"General"}),e.jsx(Us,{size:13,className:"opacity-0 group-hover:opacity-40 transition-opacity flex-shrink-0",style:{color:"var(--platform-text-muted)"}})]})]}),ye&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Access"}),e.jsx(Nr,{value:M||void 0,onChange:k,placeholder:"Select access group",showCreateButton:!0})]}),g&&!a&&e.jsxs("p",{className:"text-xs italic px-1",style:{color:"rgba(255,255,255,0.5)"},children:["These preferences are saved for future uploads. You can edit them in"," ",e.jsx("button",{type:"button",onClick:()=>n("/org/settings?tab=content"),className:"underline transition-colors hover:opacity-80",style:{color:"var(--gold)",background:"none",border:"none",padding:0,font:"inherit",curs
8or:"pointer"},children:"Org Settings > Content"}),"."]}),Z&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Summary"}),e.jsx("textarea",{className:"dialog-textarea text-sm",value:y,onChange:F=>I(F.target.value),placeholder:"Optional. Vision AI will auto-describe if left blank.",rows:2})]}),e.jsx(gi,{open:pe.open,onOpenChange:pe.setOpen,onConfirm:pe.confirmPublish,actionLabel:"Upload"}),e.jsxs("div",{className:"flex justify-end gap-3 pt-3 border-t border-white/[0.08]",children:[e.jsx(q,{variant:"secondary",onClick:r,disabled:T,children:"Cancel"}),e.jsx(q,{variant:"primary",onClick:pe.requestPublish,disabled:de,loading:T,children:T&&O?`Uploading ${O.current} of ${O.total}`:T?"Uploading...":L?"Upload":`Upload ${E} Files`})]})]},"file")}function Gm({urlValue:t,isEditingUrl:s,onUrlChange:r,onEditingUrlChange:n,onReset:a,title:o,onTitleChange:d,summary:g,onSummaryChange:c,departmentId:u,onDepartmentChange:h,orgType:x,isUploading:m,generatingSummary:f,onGenerateSummary:p,onSubmit:v,autoFocusInput:y=!0}){const[I,M]=i.useState(!1),[k,S]=i.useState(""),T=as.useRef(null),O=()=>{var $;const l=(($=T.current)==null?void 0:$.value.trim())||"";if(ur(l)){const Q=En(l);Q&&(r(Q),n(!1),d(Hr(Q)))}},w=x===Oe.BUSINESS||x===Oe.INTERNAL,b=!!t&&!s,P=m||!t.trim()||!o.trim()||w&&!u;return e.jsxs(is.div,{variants:ks,initial:"initial",animate:"animate",exit:"exit",className:"flex flex-col gap-4",children:[!t||s?e.jsxs("div",{className:"relative flex items-center",children:[e.jsx("div",{className:"absolute left-3 pointer-events-none",style:{color:"rgba(255,255,255,0.45)"},children:e.jsx(Dn,{size:18})}),e.jsx("input",{ref:T,type:"text",className:"dialog-input dialog-input-with-icon text-sm flex-1",style:{paddingRight:"3rem"},placeholder:"Paste a URL to import...",defaultValue:s?t:"",autoFocus:y,"aria-label":"URL to import",onPaste:l=>{if(!s){const $=l.clipboardData.getData("text").trim();if(ur($)){const Q=En($);Q&&(l.preventDefault(),r(Q),n(!1),d(Hr(Q)))}}},onKeyDown:l=>{l.key==="Escape"&&(s&&t?n(!1):a()),l.key==="Enter"&&(l.preventDefault(),O())}},s?"editing":"new"),s?e.jsx(q,{variant:"ghost",size:"icon-sm",className:"absolute right-2",onClick:()=>n(!1),"aria-label":"Cancel editing",children:e.jsx(at,{size:18})}):e.jsx(q,{variant:"primary",size:"icon-sm",className:"absolute right-2",onClick:O,"aria-label":"Import URL",children:e.jsx(Ia,{size:16})})]}):e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 bg-gold-icon-bg-active",children:e.jsx(Dn,{size:20,className:"text-gold-icon"})}),e.jsx("div",{className:"flex-1 min-w-0 text-sm truncate",style:{color:"var(--platform-text-primary)"},children:t}),e.jsx(q,{variant:"ghost",size:"icon-sm",onClick:()=>n(!0),"aria-label":"Edit URL",children:e.jsx(Us,{size:14,style:{color:"var(--platform-text-muted)"}})})]}),b&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Title"}),I?e.jsx("input",{className:"dialog-input text-sm",value:o,onChange:l=>d(l.target.value),onBlur:()=>M(!1),onKeyDown:l=>{l.key==="Enter"&&M(!1),l.key==="Escape"&&(d(k),M(!1))},autoFocus:!0,"aria-label":"Document title"}):e.jsxs("button",{className:"flex items-center gap-2 text-left w-full group dialog-input",onClick:()=>{S(o),M(!0)},style:{cursor:"text"},children:[e.jsx(Al,{size:15,className:"flex-shrink-0",style:{color:"var(--platform-text-muted)"}}),e.jsx("span",{className:"text-sm flex-1 truncate",style:{color:"var(--platform-text-primary)"},children:o||"Untitled"}),e.jsx(Us,{size:13,className:"opacity-0 group-hover:opacity-40 transition-opacity flex-shrink-0",style:{color:"var(--platform-text-muted)"}})]})]}),w&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Access"}),e.jsx(Nr,{value:u||void 0,onChange:h,placeholder:"Select access group",showCreateButton:!0})]}),!g.trim()&&t&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl",style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.1)"},children:[e.jsx("div",{className:"w-9 h-9 rounded-xl flex items-center justify-center flex-shrink-0 bg-gold-icon-bg-active",children:e.jsx(Zr,{size:18,className:"text-gold-icon"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium block",style:{color:"rgba(255,255,255,0.9)"},children:"Let AI write a summary"}),e.jsx("span",{className:"text-xs",style:{color:"rgba(255,255,255,0.45)"},children:"Based on the URL content"})]}),e.jsx(q,{variant:"primary",size:"sm",onClick:()=>void p(),disabled:f||!t.trim(),loading:f,children:f?"Generating...":e.jsxs(e.Fragment,{children:[e.jsx(Bs,{size:14}),"Generate"]})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Summary"}),e.jsx("textarea",{className:"dialog-textarea text-sm",value:g,onChange:l=>c(l.target.value),placeholder:"A brief description of what this URL contains...",rows:3}),g.trim()&&e.jsx("div",{className:"flex justify-end",children:e.jsx(q,{variant:"utility",size:"sm",onClick:()=>void p(),disabled:f||!t.trim(),loading:f,children:f?"Regenerating...":e.jsxs(e.Fragment,{children:[e.jsx(Zr,{size:12}),"Regenerate with AI"]})})})]}),e.jsxs("div",{className:"flex justify-end gap-3 pt-3 border-t border-white/[0.08]",children:[e.jsx(q,{variant:"secondary",onClick:a,disabled:m,children:"Cancel"}),e.jsx(q,{variant:"primary",onClick:v,disabled:P,loading:m,children:m?"Importing...":"Import"})]})]})]},"url")}function Vm({suggestions:t,selectedTags:s,onToggle:r,maxTags:n}){if(t.length===0)return null;const a=t.filter(o=>!s.some(d=>d.toLowerCase()===o.toLowerCase()));return s.length>=n||a.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[e.jsx("span",{className:"text-[11px] font-medium uppercase tracking-wider mr-0.5",style:{color:"rgba(255, 255, 255, 0.35)"},children:"Suggested:"}),a.map(o=>e.jsxs(q,{variant:"utility",size:"sm",onClick:()=>r(o),className:"bg-white/[0.05] border border-white/[0.06] text-white/60 hover:bg-white/[0.08]",children:["+ ",o]},o))]})}function Km({title:t,textContent:s,tags:r,tagInput:n,tagSuggestions:a,isUploading:o,isEnhancingContent:d,onTitleChange:g,onTextContentChange:c,onTagsChange:u,onTagInputChange:h,onAddTag:x,onSuggestionToggle:m,onReset:f,onPublish:p,departmentId:v=null,onEnhanceContent:y,onVoiceClick:I,onStopRecording:M,onStartFromPrompt:k,onRecordNote:S,isRecording:T=!1,isProcessingAudio:O=!1}){const{org:w}=Ve(),b=(w==null?void 0:w.org_type)===Oe.BUSINESS||(w==null?void 0:w.org_type)===Oe.INTERNAL,P=xi({isBusinessOrg:b,departmentId:v,onPublish:p});return e.jsxs(is.div,{variants:ks,initial:"initial",animate:"animate",exit:"exit",className:"flex flex-col gap-0",children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"px-6 pt-5 pb-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-3 pb-3",style:{boxShadow:"0 1px 0 rgba(255,255,255,0.06)"},children:[e.jsx(ps,{size:17,className:"flex-shrink-0",style:{color:"var(--gold, rgba(197,160,90,0.7))"}}),e.jsx("input",{type:"text",className:"flex-1 bg-transparent border-none outline-none text-[15px] font-medium",style:{color:"var(--platform-text-primary, rgba(255,255,255,0.95))"},value:t,onChange:l=>g(l.target.value),placeholder:"Title...","aria-label":"Document title",autoFocus:!s}),e.jsx(q,{variant:"ghost",size:"icon-sm",onClick:f,"aria-label":"Cancel",children:e.jsx(at,{size:16})})]}),e.jsxs("div",{className:"flex items-center gap-2 py-2.5 flex-wrap",style:{boxShadow:"0 1px 0 rgba(255,255,255,0.06)"},children:[e.jsx(Pl,{size:15,className:"flex-shrink-0",style:{color:"rgba(255,255,255,0.35)"}}),r.map(l=>e.jsxs(yt,{variant:"accent",className:"gap-1",children:[l,e.jsx("button",{className:"ml-0.5 hover:opacity-70 transition-opacity",onClick:()=>u(r.filter($=>$!==l)),"aria-label":`Remove tag ${l}`,children:e.jsx(at,{size:8})})]},l)),r.length<dr&&e.jsx("input",{type:"text",className:"bg-transparent border-none outline-none text-[13px] min-w-[60px] flex-1",style:{color:"rgba(255,255,255,0.6)"},value:n,onChange:l=>h(l.target.value),"aria-label":"Add tag",onKeyDown:l=>{(l.key==="Enter"||l.key===",")&&(l.preventDefault(),x())},placeholder:"Add tags..."})]})]}),(k||S)&&!s.trim()&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 px-6 pt-3",children:[k&&e.jsxs(q,{variant:"secondary",size:"sm",onClick:k,disabled:o,children:[e.jsx(Bs,{size:14}),"Start from a prompt"]}),S&&e.jsxs(q,{variant:"secondary",size:"sm",onClick:S,disabled:o||T||O,children:[e.jsx(fr,{size:14}),"Record a note"]})]}),e.jsx("div",{className:"px-5 py-3",children:e.jsx(ol,{content:s,onChange:c,placeholder:"Start writing, or type / for headings, lists, and more...",onAIEnhance:(l,$)=>{l&&y(l,$)},isEnhancingContent:d,onVoiceClick:I,isRecording:T,isProcessingAudio:O,onStopRecording:M,showActionCards:!1,minHeight:"320px"})}),e.jsxs("div",{className:"flex items-center gap-3 px-6 py-3 border-t border-white/[0.1]",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Vm,{suggestions:a,selectedTags:r,onToggle:m,maxTags:dr})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx(q,{variant:"secondary",size:"sm",onClick:f,disabled:o,children:"Cancel"}),e.jsx(q,{variant:"primary",size:"sm",onClick:P.requestPublish,disabled:o||!s.trim(),loading:o,children:"Publish"})]})]})]}),b&&e.jsx(gi,{open:P.open,onOpenChange:P.setOpen,onConfirm:P.confirmPublish})]},"text")}function Wm({aiPrompt:t,isGeneratingAI:s,onPromptChange:r,onGenerate:n,onReset:a}){return e.jsxs(is.div,{variants:ks,initial:"initial",animate:"animate",exit:"exit",className:"flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bs,{size:16,style:{color:"var(--gold)"}}),e.jsx("label",{className:"dialog-label",style:{marginBottom:0},children:"Prompt"})]}),e.jsx("textarea",{className:"dialog-textarea text-sm","data-ai-create-textarea":"true",value:t,onChange:o=>r(o.target.value),placeholder:"Describe what you want to create...",autoFocus:!0,rows:3}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("label",{className:"dialog-label",children:"Qu
8ick templates"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(q,{variant:"utility",onClick:()=>r("Create meeting notes with sections for attendees, agenda, discussion, and action items"),children:"Meeting notes"}),e.jsx(q,{variant:"utility",onClick:()=>r("Create a how-to guide with clear step-by-step instructions"),children:"How-to guide"}),e.jsx(q,{variant:"utility",onClick:()=>r("Create a reusable template with placeholders and structured sections"),children:"Template"}),e.jsx(q,{variant:"utility",onClick:()=>r("Create a project brief with objectives, scope, timeline, and deliverables"),children:"Project brief"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1",children:[e.jsx(Bs,{size:14,style:{color:"var(--gold)"}}),e.jsx("span",{className:"text-xs",style:{color:"rgba(255,255,255,0.45)"},children:"AI-powered"})]}),e.jsx(q,{variant:"secondary",onClick:a,children:"Cancel"}),e.jsx(q,{variant:"primary",onClick:()=>void n(),disabled:!t.trim()||s,loading:s,children:s?"Generating...":e.jsxs(e.Fragment,{children:[e.jsx(Zr,{size:16}),"Generate"]})})]})]},"ai-create")}const na=32,Ym=Array.from({length:na},(t,s)=>({delay:(s*.07+Math.sin(s*.9)*.12)%1.2,maxScale:.35+.65*Math.sin(s/(na-1)*Math.PI)}));function Hm({active:t}){return e.jsx("div",{className:"flex items-center justify-center gap-[3px]",style:{height:48},"aria-hidden":!0,children:Ym.map((s,r)=>e.jsx("div",{className:"rounded-full",style:{width:2.5,height:t?`${s.maxScale*100}%`:3,backgroundColor:t?"var(--gold)":"rgba(255, 255, 255, 0.15)",opacity:t?.5+s.maxScale*.5:.4,transition:t?"none":"all 0.5s ease",animation:t?`voiceBar ${.6+s.delay*.4}s ease-in-out ${s.delay}s infinite alternate`:"none"}},r))})}const aa="voice-tab-keyframes";function Qm(){if(typeof document>"u"||document.getElementById(aa))return;const t=document.createElement("style");t.id=aa,t.textContent=`
9    @keyframes voiceBar {
10      0%   { transform: scaleY(0.25); }
11      100% { transform: scaleY(1); }
12    }
13    @keyframes voicePulse {
14      0%, 100% { opacity: 0; transform: scale(0.85); }
15      50%      { opacity: 1; transform: scale(1); }
16    }
17  `,document.head.appendChild(t)}function Jm({isRecording:t,recordingTime:s,onVoiceToggle:r,onReset:n,reviewState:a,isSaving:o,orgType:d,departmentId:g,onDepartmentChange:c,onReviewTitleChange:u,onSave:h,onDiscard:x,maxDurationWarning:m}){as.useEffect(Qm,[]);const f=d===Oe.BUSINESS||d===Oe.INTERNAL;return a?e.jsx(is.div,{variants:ks,initial:"initial",animate:"animate",exit:"exit",className:"flex flex-col gap-5 py-6",children:e.jsxs("div",{className:Ut.card,children:[e.jsxs("div",{className:"flex flex-col gap-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-medium",style:{backgroundColor:"rgba(197, 160, 90, 0.10)",border:"1px solid rgba(197, 160, 90, 0.20)",color:"var(--gold)"},children:[e.jsx(fr,{size:12}),"Audio recording"]}),e.jsxs(yt,{variant:"accent",className:"flex items-center gap-1.5",children:[e.jsx(Ll,{size:12}),In(a.duration)]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"dialog-label",children:"Title"}),e.jsx("input",{type:"text",className:"w-full bg-transparent outline-none text-[15px] font-medium pb-1.5",style:{color:"var(--platform-text-primary, rgba(255,255,255,0.95))",borderBottom:"1px solid rgba(255,255,255,0.12)"},value:a.title,onChange:p=>u(p.target.value),onFocus:p=>{p.currentTarget.style.borderBottomColor="var(--gold)"},onBlur:p=>{p.currentTarget.style.borderBottomColor="rgba(255,255,255,0.12)"},"aria-label":"Voice note title",autoFocus:!0})]}),e.jsx("div",{className:"border-t",style:{borderColor:"rgba(255,255,255,0.06)"}}),e.jsxs("div",{children:[e.jsx("label",{className:"dialog-label",children:"Transcript"}),e.jsx("div",{className:"text-[13px] leading-relaxed overflow-y-auto rounded-lg p-3",style:{maxHeight:200,color:a.transcript?"rgba(255,255,255,0.6)":"rgba(255,255,255,0.35)",backgroundColor:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)",fontStyle:a.transcript?"normal":"italic"},role:"region","aria-label":"Transcript preview",children:a.transcript||"Transcription unavailable. The audio will still be saved."})]}),f&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"dialog-label",children:"Access"}),e.jsx(Nr,{value:g||void 0,onChange:c,placeholder:"Select access group",showCreateButton:!0})]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-white/[0.06]",children:[e.jsx(q,{variant:"secondary",size:"sm",onClick:x,disabled:o,children:"Discard"}),e.jsx(q,{variant:"primary",size:"sm",onClick:h,loading:o,children:"Save Voice Note"})]})]})},"review"):e.jsxs(is.div,{variants:ks,initial:"initial",animate:"animate",exit:"exit",className:"flex flex-col items-center justify-center py-16 select-none",style:{minHeight:360},children:[e.jsxs("div",{className:"relative mb-8",children:[t&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -inset-3 rounded-full",style:{border:"1px solid rgba(197, 160, 90, 0.12)",animation:"voicePulse 3s ease-in-out infinite"}}),e.jsx("div",{className:"absolute -inset-6 rounded-full",style:{border:"1px solid rgba(197, 160, 90, 0.06)",animation:"voicePulse 3s ease-in-out 0.5s infinite"}})]}),e.jsx("button",{className:"relative flex items-center justify-center rounded-full transition-all duration-300 cursor-pointer",style:{width:88,height:88,backgroundColor:t?"rgba(197, 160, 90, 0.14)":"rgba(255, 255, 255, 0.05)",border:t?"1.5px solid rgba(197, 160, 90, 0.30)":"1.5px solid rgba(255, 255, 255, 0.08)",boxShadow:t?"0 0 40px rgba(197, 160, 90, 0.10), inset 0 0 20px rgba(197, 160, 90, 0.05)":"none"},onClick:()=>void r(),"aria-label":t?"Stop recording":"Start recording",children:e.jsx(Va,{mode:"wait",children:t?e.jsx(is.div,{initial:{scale:.7,opacity:0}
17,animate:{scale:1,opacity:1},exit:{scale:.7,opacity:0},transition:{duration:.15},children:e.jsx(Fl,{size:22,fill:"var(--gold)",style:{color:"var(--gold)"}})},"stop"):e.jsx(is.div,{initial:{scale:.7,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.7,opacity:0},transition:{duration:.15},children:e.jsx(fr,{size:30,style:{color:"rgba(255,255,255,0.50)"}})},"mic")})})]}),e.jsx("div",{className:"mb-6 w-64",children:e.jsx(Hm,{active:t})}),e.jsx("div",{className:"text-[2rem] font-light tracking-wide mb-2",style:{fontVariantNumeric:"tabular-nums",color:t?"var(--gold)":"rgba(255,255,255,0.35)",transition:"color 0.3s ease"},children:In(s)}),e.jsx("div",{className:"text-[13px] tracking-wide uppercase mb-8",style:{color:t?"rgba(255,255,255,0.45)":"rgba(255,255,255,0.25)",letterSpacing:"0.08em",transition:"color 0.3s ease"},children:t?"Recording":"Tap to record"}),m&&e.jsx("div",{className:"text-xs mb-4",style:{color:"var(--gold)"},role:"status",children:"Recording will stop at 10:00"}),e.jsx(q,{variant:"secondary",onClick:n,children:"Cancel"})]},"voice")}const er={file:"file",write:"text"},Xm={file:"file",url:"file",text:"write",voice:"write","ai-create":"write"};function Zm({onCreateText:t,onUploadComplete:s,onModeChange:r,initialTab:n="file",embedded:a=!1,showSyncMethod:o=!1,hideMethodChips:d=!1}){var F,Y,ie,oe,C,A,B,te,he,ue,Ae,Ce,xe,$e;const[g,c]=Es(),u=Cs(),h=g.get("tab")||n,x=o&&h===Rt,m=x?"file":sn(h)??n,{orgId:f}=Ve(),{user:p}=Is(),v=g.get("folder"),y=Zo(f,(p==null?void 0:p.id)??null,!!v),I=(F=y.data)==null?void 0:F.find(se=>se.id===v),M=!!v&&(y.isPending||y.isError||!I),k=()=>c(se=>{const ke=new URLSearchParams(se);return ke.delete("folder"),ke},{replace:!0});i.useEffect(()=>{v&&(m!=="file"||x)&&k()},[m,x,v]);const{isAdminOrOwner:S}=Sa(),{data:T}=Ua(),O=(T==null?void 0:T.some(se=>se.connected))??!1,[w,b]=i.useState(()=>localStorage.getItem("dismiss-integrations-cta")==="true"),P=!o&&S&&!O&&!w,l=yc({initialMode:er[x?n:m],libraryFolderId:I==null?void 0:I.id,uploadDestinationBlocked:M,onCreateText:t,onUploadComplete:s,onModeChange:r,variant:"hero"}),$=i.useRef(!1);i.useEffect(()=>{if(x)return;const se=m==="file"&&l.urlValue.trim()?"url":er[m];l.mode!==se&&($.current=!0,l.setMode(se),se==="url"?l.setIconState("url"):se==="text"?l.setIconState("text"):se==="file"?l.setIconState("file"):l.setIconState("upload"))},[m,x]),i.useEffect(()=>{if(x)return;if($.current){$.current=!1;return}const se=Xm[l.mode];se&&se!==m&&c(ke=>{const Ee=new URLSearchParams(ke);return Ee.set("tab",se),Ee},{replace:!0})},[l.mode,m,c,x]);const[Q,re]=i.useState(!1),K=()=>{re(!0),l.setMode("ai-create"),l.setIconState("text")},D=()=>{re(!1),l.mode==="ai-create"&&(l.setMode("text"),l.setIconState("text"))};i.useEffect(()=>{Q&&l.mode==="text"&&re(!1)},[Q,l.mode]);const E=i.useRef(!1);i.useEffect(()=>{E.current||x||h!=="ai"||(E.current=!0,K())},[h,x]);const[N,L]=i.useState(!1),U=()=>L(!0),Z=()=>{l.isRecording||l.isProcessing||(L(!1),l.voiceReviewState&&l.handleVoiceNoteDiscard())},le=i.useRef(!1);i.useEffect(()=>{le.current||x||h!=="voice"||(le.current=!0,L(!0))},[h,x]);const De=l.selectedFiles.length>0,fe=!De&&(!!l.urlValue||l.isEditingUrl),ye=se=>{l.setUrlValue(se),se.trim()?(l.setMode("url"),l.setIconState("url")):De||(l.setMode("file"),l.setIconState("file"))};wr(a?"Add":"Add Content");const pe=d?null:e.jsx(Wa,{showSyncMethod:o,onManualTabChange:se=>{$.current=!0,l.setMode(er[se]);const ke=er[se];ke==="url"?l.setIconState("url"):ke==="text"?l.setIconState("text"):ke==="file"?l.setIconState("file"):l.setIconState("upload")}}),de=e.jsxs(e.Fragment,{children:[a?null:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsx(rn,{title:"Add Content",subtitle:"Import documents, URLs, or create content.",rightContent:e.jsx(Ac,{orgId:f})}),pe]}),e.jsx("div",{className:"border-t border-[var(--gold-border)]"}),P&&e.jsxs("div",{role:"status",className:"flex items-center gap-3 px-4 py-3 rounded-xl animate-in fade-in duration-200",style:{backgroundColor:"rgba(197, 160, 90, 0.06)",border:"1px solid rgba(197, 160, 90, 0.18)"},children:[e.jsx("div",{className:"flex items-center justify-center w-8 h-8 rounded-lg shrink-0 bg-gold-icon-bg-active",children:e.jsx(Ta,{className:"h-4 w-4 text-gold-icon"})}),e.jsx("p",{className:"text-[13px] flex-1",style:{color:"var(--platform-text-secondary)"},children:"Connect your tools to automatically sync knowledge"}),e.jsx(q,{variant:"secondary",size:"sm",onClick:()=>{u(qt.UPLOAD_CONNECTED)},children:"Set up integrations"}),e.jsx(q,{variant:"ghost",size:"icon-xs",type:"button",onClick:()=>{localStorage.setItem("dismiss-integrations-cta","true"),b(!0)},"aria-label":"Dismiss integrations banner",children:e.jsx(at,{className:"h-3.5 w-3.5"})})]})]}),v&&m==="file"&&!x&&e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-white/10 p-4",children:[e.jsx("p",{className:"flex-1 text-sm",role:M?"alert":"status",children:y.isPending?"Loading destination…":y.isError?"Could not load the destination folder. Retry before uploading.":I?e.jsxs(e.Fragment,{children:["Uploading files to ",e.jsx("strong",{children:I.name}),". Choose Access separately; folder membership does not change who can read them."]}):"This folder is unavailable. Choose another destination in the Library."}),y.isError&&e.jsx(q,{variant:"secondary",size:"sm",onClick:()=>void y.refetch(),children:"Retry"}),e.jsx(q,{variant:"ghost",size:"sm",disabled:l.isUploading,onClick:k,children:"Clear destination"})]}),e.jsx("div",{className:Ut.pageContent,children:x?e.jsx(hi,{children:e.jsx(fi,{embedded:!0})}):e.jsx("div",{className:Ue(Ut.card,m==="write"?"!p-0 flex flex-col":"flex flex-col gap-4"),children:l.isProcessing?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-4",children:[e.jsx(it,{className:"w-12 h-12 animate-spin",style:{color:"var(--gold)"}}),e.jsx("div",{className:"text-[15px]",style:{color:"rgba(255,255,255,0.7)"},children:"Processing audio..."})]}):e.jsxs(Va,{mode:"wait",initial:!1,children:[m==="file"&&e.jsxs("div",{className:"flex flex-col gap-4",children:[(!fe||!!v)&&e.jsx(qm,{selectedFiles:l.selectedFiles,onRemoveFile:l.handleRemoveFile,onReset:l.handleReset,onNavigate:l.navigate,batchDetection:l.batchDetection,onFamilyConfirm:l.handleFamilyConfirm,onFamilyDismiss:l.handleFamilyDismiss,showPreferencesSaved:l.showPreferencesSaved,selectedDocType:l.selectedDocType,onDocTypeSelect:l.handleDocTypeSelect,suggestedType:l.suggestedType,customChipTypes:l.customChipTypes,fileInputRef:l.fileInputRef,isDragOver:l.isDragOver,title:l.title,onTitleChange:l.setTitle,summary:l.summary,onSummaryChange:l.setSummary,departmentId:l.departmentId,onDepartmentChange:l.setDepartmentId,orgType:l.orgType,isUploading:l.isUploading,uploadProgress:l.uploadProgress,uploadFileProgress:l.uploadFileProgress,uploadDisabled:M,onUpload:se=>l.handleFileUpload(se)}),!v&&!De&&!fe&&e.jsxs("div",{className:"flex items-center gap-3","aria-hidden":"true",children:[e.jsx("div",{className:"flex-1 border-t border-white/[0.08]"}),e.jsx("span",{className:"text-[11px] uppercase tracking-[0.18em]",style:{color:"var(--platform-text-muted)"},children:"or"}),e.jsx("div",{className:"flex-1 border-t border-white/[0.08]"})]}),!v&&!De&&e.jsx(Gm,{urlValue:l.urlValue,isEditingUrl:l.isEditingUrl,onUrlChange:ye,onEditingUrlChange:l.setIsEditingUrl,autoFocusInput:!1,onReset:l.handleReset,title:l.title,onTitleChange:l.setTitle,summary:l.summary,onSummaryChange:l.setSummary,departmentId:l.departmentId,onDepartmentChange:l.setDepartmentId,orgType:l.orgType,isUploading:l.isUploading,generatingSummary:l.generatingSummary,onGenerateSummary:()=>void l.handleGenerateSummary(),onSubmit:()=>void l.handleUrlSubmit()})]},"upload"),m==="write"&&e.jsx(Km,{title:l.title,textContent:l.textContent,tags:l.tags,tagInput:l.tagInput,tagSuggestions:l.tagSuggestions,isUploading:l.isUploading,isEnhancingContent:l.isEnhancingContent,isRecording:l.isRecording,isProcessingAudio:l.isProcessing,onTitleChange:l.setTitle,onTextContentChange:l.setTextContent,onTagsChange:l.setTags,onTagInputChange:l.setTagInput,onAddTag:l.handleAddTag,onSuggestionToggle:l.handleSuggestionToggle,onReset:l.handleReset,departmentId:l.departmentId,onPublish:se=>void l.handleTextPublish(se),onEnhanceContent:(se,ke)=>void l.handleEnhanceContent(se,ke),onVoiceClick:()=>void l.handleVoiceToggle(),onStopRecording:()=>{var se;return(se=l.voiceRef.current)==null?void 0:se.stopRecording()},onStartFromPrompt:K,onRecordNote:U})]})})}),e.jsx("input",{ref:l.fileInputRef,type:"file",multiple:!0,className:"hidden",onChange:se=>l.handleFileSelect(se.target.files),"aria-label":"Upload file",accept:".pdf,.doc,.docx,.txt,.md,.xls,.xlsx,.csv,.jpg,.jpeg,.png,.gif,.mp3,.m4a,.wav,.pages,.numbers,.key"}),(((Y=l.duplicateCandidate)==null?void 0:Y.existingDoc)||((ie=l.textDuplicateInfo)==null?void 0:ie.existingDoc))&&e.jsx(xl,{open:l.showDuplicateDialog,onOpenChange:se=>{l.setShowDuplicateDialog(se),se||l.setTextDuplicateInfo(null)},existingDoc:((oe=l.duplicateCandidate)==null?void 0:oe.existingDoc)??((C=l.textDuplicateInfo)==null?void 0:C.existingDoc),newFileName:((A=l.duplicateCandidate)==null?void 0:A.newFileName)??((B=l.textDuplicateInfo)==null?void 0:B.newTitle)??"",source:l.textDuplicateInfo?"quick-write":"upload",matchType:l.textDuplicateInfo?"title":void 0,onBlock:l.handleBlockDuplicate,onCreateVersion:l.handleShowVersionConfirmation,onEditExisting:l.handleEditExistingFromDuplicate,onUploadAnyway:l.handleShowUploadAnywayConfirmation}),(((te=l.updateCandidate)==null?void 0:te.existingDoc)||((he=l.duplicateCandidate)==null?void 0:he.existingDoc))&&e.jsx(el,{open:l.showVersionConfirmation,hasUploadDestination:!!v,onOpenChange:l.setShowVersionConfirmation,existingDoc:((ue=l.updateCandidate)==null?void 0:ue.existingDoc)??((Ae=l.duplicateCandidate)==null?void 0:Ae.existingDoc),newFileName:((Ce=l.duplicateCandidate)==null?void 0:Ce.newFileName)||((xe=l.selectedFiles[0])==null?void 0:xe.name)||"",onConfirm:()=>void l.handleCreateVersionFromDuplicate(),onCancel:()=>{l.setShowVersionConfirmation(!1),l.setUpdateCandidate(null)},onUploadAsNew:()=>void l.handleUploadAsNewFromVersion()}),(($e=l.duplicateCandidate)==null?void 0:$e.existingDoc)&&e.jsx(bc,{open:l.showU
17ploadAnywayConfirmation,onOpenChange:l.setShowUploadAnywayConfirmation,existingDoc:l.duplicateCandidate.existingDoc,newFileName:l.duplicateCandidate.newFileName||"",onConfirm:()=>void l.handleUploadAnyway(),onCancel:()=>{l.setShowUploadAnywayConfirmation(!1)}}),l.enhancePreview&&e.jsx(ll,{before:l.enhancePreview.before,after:l.enhancePreview.after,changeSummary:l.enhancePreview.changeSummary,enhancementType:l.enhancePreview.enhancementType,onAccept:l.acceptEnhancePreview,onReject:l.rejectEnhancePreview}),e.jsx(nt,{open:Q,onOpenChange:se=>{se||D()},tier:"form",title:"Start from a prompt",icon:e.jsx(Bs,{}),description:"Describe what you want and it lands in your editor, ready to edit and publish.",maxWidth:"xl",isLoading:l.isGeneratingAI,children:e.jsx(Wm,{aiPrompt:l.aiPrompt,isGeneratingAI:l.isGeneratingAI,onPromptChange:l.setAiPrompt,onGenerate:()=>void l.handleGenerateAI(),onReset:()=>{l.setAiPrompt(""),D()}})}),e.jsx(nt,{open:N,onOpenChange:se=>{se||Z()},tier:"form",title:"Record a note",icon:e.jsx(fr,{}),description:"Record now and it is saved as an audio document, transcript included.",children:e.jsx(Jm,{isRecording:l.isRecording,recordingTime:l.recordingTime,onVoiceToggle:()=>void l.handleVoiceToggle(),onReset:()=>{l.isRecording||l.isProcessing?l.handleReset():Z()},reviewState:l.voiceReviewState,isSaving:l.isSavingVoiceNote,orgType:l.orgType,departmentId:l.departmentId,onDepartmentChange:l.setDepartmentId,onReviewTitleChange:l.handleVoiceReviewTitleChange,onSave:()=>void l.handleVoiceNoteSave(),onDiscard:()=>{l.handleVoiceNoteDiscard(),L(!1)},maxDurationWarning:l.maxDurationWarning})}),e.jsx(Pc,{open:l.showBatchSummary,on_close:()=>l.setShowBatchSummary(!1),results:l.batchResults}),e.jsx("div",{style:{display:"none"},children:e.jsx(Oo,{ref:l.voiceRef,onTranscript:N?l.handleVoiceNoteTranscript:l.handleVoiceTranscript,onAudioBlob:se=>{N&&l.setVoiceBlob(se)},onRecordingChange:se=>{l.setIsRecording(se),se||l.stopRecordingTimer()},onProcessingChange:l.setIsProcessing})})]});return a?e.jsx("div",{className:"flex flex-col gap-6",onDragOver:l.handleDragOver,onDragLeave:l.handleDragLeave,onDrop:l.handleDrop,children:de}):e.jsx(Na,{children:e.jsx("div",{className:Ue(Ut.platformPage,"flex flex-col gap-8"),onDragOver:l.handleDragOver,onDragLeave:l.handleDragLeave,onDrop:l.handleDrop,children:de})})}function ef(){const{orgId:t}=Ve();return He({queryKey:["permanently-failed-extractions",t],queryFn:async()=>{if(!t)return[];const{data:s,error:r}=await X.from("v_permanently_failed_extractions").select("doc_id, org_id, title, entity_extraction_retries, entity_extraction_error, entity_extraction_attempted_at, doc_created_at, org_name").eq("org_id",t).order("entity_extraction_attempted_at",{ascending:!1});if(r)throw r;return s??[]},enabled:!!t,staleTime:3e4})}function bi(){const{role:t}=Ve(),s=$o(t),r=Gs(t),n=t===Mo.MANAGER;return{canManageContent:s,canDeleteContent:r,canResolveDuplicates:s,canDeleteDuplicates:r,canCreateDepartments:s,canEditDepartments:s,canDeleteDepartments:r,canAssignDeptMembers:s,canInviteUsers:s,canChangeRoles:r,canRemoveMembers:r,canViewAnalytics:s,canViewInsights:s,canViewHealth:s,canViewQueue:s,canCreateBundles:s,canRevokeBundleLinks:r,canManageOrganization:r,canManageAgents:r,canManageIntegrations:r,canViewBilling:r,isManager:n,isManagerOrAbove:s,isAdminOrAbove:r}}function vs({icon:t,title:s,badgeVariant:r,badgeLabel:n,detail:a,to:o,linkLabel:d,action:g,onToggleExpanded:c,expanded:u=!1,expandLabel:h,expandedContent:x}){const m=!!c,f=m||!!o,p=i.useId();return e.jsxs("li",{children:[e.jsxs("div",{className:Ue("group relative flex items-start gap-3 px-6 py-3",f&&"transition-colors hover:bg-white/5 focus-within:bg-white/5",u&&"bg-white/[0.04]"),children:[m?e.jsx("button",{type:"button",onClick:c,"aria-expanded":u,"aria-controls":u?p:void 0,className:"absolute inset-0 z-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-white/25",children:e.jsx("span",{className:"sr-only",children:h??s})}):o?e.jsx(zs,{to:o,className:"absolute inset-0 z-0 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-white/25",children:e.jsx("span",{className:"sr-only",children:d??s})}
17):null,e.jsx("span",{"aria-hidden":!0,className:"pointer-events-none relative z-10 mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center",style:{color:"var(--platform-text-muted)"},children:t}),e.jsxs("div",{className:"pointer-events-none relative z-10 min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-sm",style:{color:"var(--platform-text)"},children:s}),e.jsx(yt,{variant:r,size:"sm",className:"shrink-0",children:n})]}),a]}),g?e.jsx("div",{className:"relative z-10 shrink-0",children:g}):null,m?e.jsx(Vs,{"aria-hidden":!0,className:Ue("pointer-events-none relative z-10 mt-0.5 h-4 w-4 shrink-0 transition-transform motion-reduce:transition-none",u&&"rotate-180"),style:{color:"var(--platform-text-muted)"}}):f?e.jsx(Ts,{"aria-hidden":!0,className:"pointer-events-none relative z-10 mt-0.5 h-4 w-4 shrink-0 opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 motion-reduce:transition-none",style:{color:"var(--platform-text-muted)"}}):null]}),m&&u&&x?e.jsx("div",{id:p,className:"pb-3 pl-[3.25rem] pr-6 pt-2",children:x}):null]})}function bs({parts:t}){const s=t.filter(r=>!!r);return s.length===0?null:e.jsx("p",{className:"mt-0.5 truncate text-[11px]",style:{color:"var(--platform-text-muted)"},children:s.join(" · ")})}function ia(t,s){const r=t==null?void 0:t[s];return typeof r=="string"&&r.length>0?r:void 0}function tf({issue:t,onRetry:s,onClear:r,retrying:n,clearing:a,disabled:o}){const d=t.status===Se.FAILED,g=t.file_name||"Untitled file",c=d?null:ni(t.metadata,g);return e.jsxs("li",{className:"flex items-start gap-2 py-1.5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate text-xs",style:{color:"var(--platform-text)"},children:g}),e.jsx(yt,{variant:d?"error":c!=null&&c.needsDecision?"warning":"neutral",size:"sm",className:"shrink-0",children:d?"Failed":(c==null?void 0:c.label)??"Skipped"})]}),e.jsx("p",{className:"mt-0.5 text-[11px]",style:{color:"var(--platform-text-muted)"},children:c?c.detail:Ir(t.error_message,t.metadata)})]}),c!=null&&c.needsDecision?e.jsx("div",{className:"shrink-0",children:e.jsx(ai,{stagingId:t.id,fileName:g,existingTitle:ia(t.metadata,"existing_title"),existingDocId:ia(t.metadata,"existing_doc_id")})}):d?e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(q,{type:"button",variant:"ghost",size:"xs",disabled:o,loading:n,"aria-label":`Retry ${g}`,onClick:()=>s(t.id),children:"Retry"}),e.jsx(q,{type:"button",variant:"ghost",size:"xs",disabled:o,loading:a,"aria-label":`Clear ${g}`,onClick:()=>r(t.id),children:"Clear"})]}):null]})}function sf(t,s){const r=new URL(t,"http://local");if(r.pathname!==s.pathname)return!0;const n=new URLSearchParams(s.search);for(const[a,o]of r.searchParams)if(n.get(a)!==o)return!0;return!1}function rf({batchId:t,settingsHref:s,settingsLabel:r}){const{toast:n}=ze(),a=Ki(),{data:o=[],isLoading:d,isError:g}=Qa(t),c=fn(),u=Za(),[h,x]=i.useState([]),[m,f]=i.useState([]),p=o.filter(T=>T.status===Se.FAILED),v=c.isPending||u.isPending,y=sf(s,a),I=i.useCallback(T=>{T.length!==0&&(x(T),c.mutate(T,{onSuccess:O=>{x([]),n({title:O===1?"Retrying that file":`Retrying ${O} files`,description:"They go back in the queue and sync again shortly.",variant:"success"})},onError:O=>{x([]),n({title:"Couldn't retry",description:O.message||"Please try again.",variant:"destructive"})}}))},[c,n]),M=i.useCallback(T=>I([T]),[I]),k=i.useCallback(T=>{T.length!==0&&(f(T),u.mutate(T,{onSuccess:()=>{f([])},onError:O=>{f([]),n({title:"Couldn't clear",description:O.message||"Please try again.",variant:"destructive"})}}))},[u,n]),S=i.useCallback(T=>k([T]),[k]);return e.jsxs("div",{className:"glass-inset rounded-xl px-3 py-2.5",children:[d?e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:"Loading this run's files…"}):g?e.jsx("p",{className:"text-xs",style:{color:"var(--platform-error, #f87171)"},role:"alert",children:"Couldn't load the files from this run."}):o.length===0?e.jsx("p",{className:"text-xs",style:{color:"var(--platform-text-muted)"},children:"Every file in this run came in cleanly."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2 border-b border-white/5 pb-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-[0.14em]",style:{color:"var(--platform-text-muted)"},children:p.length>
170?"Files that need attention":"Files skipped"}),p.length>0&&e.jsx(q,{type:"button",variant:"ghost",size:"xs",className:"shrink-0",disabled:v,"aria-label":`Retry all ${p.length} failed files`,onClick:()=>I(p.map(T=>T.id)),children:c.isPending&&h.length>1?"Retrying…":"Retry all failed"})]}),e.jsx("ul",{className:"divide-y divide-white/5",children:o.map(T=>e.jsx(tf,{issue:T,onRetry:M,onClear:S,retrying:c.isPending&&h.includes(T.id),clearing:u.isPending&&m.includes(T.id),disabled:v},T.id))})]}),y?e.jsx("div",{className:"mt-1 flex justify-end border-t border-white/5 pt-1.5",children:e.jsx(zs,{to:s,"aria-label":r,className:"text-[11px] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-white/25",style:{color:"var(--platform-text-muted)"},children:"Open settings"})}):null]})}const wi={google:"google_drive",trello:"trello",notion:"notion",slack:"slack",dropbox:"dropbox",webhook:"webhook-ingest",hubspot:"hubspot"},nf={webhook:"Webhook",slack:"Slack"};function oa(t){if(!t)return"Connected source";const s=nf[t];if(s)return s;const r=wi[t];return r&&Bo[r]||t}function la(t){return t&&hn(t)?zo(t):qt.UPLOAD_CONNECTED}function ca(t){if(!t)return null;const s=wi[t];return s?{source:s}:null}const af=new Set(Uo);function of(t){const s=t==null?void 0:t.source;return typeof s=="string"&&af.has(s)}function lf(t){const s=[t.is_active?`${t.completed} of ${t.total} synced`:`${t.completed} synced`];return t.failed>0&&s.push(`${t.failed} failed`),s.join(" · ")}function da(t){return t.is_active?{variant:"info",label:"Syncing"}:t.failed>0&&t.completed===0?{variant:"error",label:"Failed"}:t.failed>0?{variant:"warning",label:"Completed with issues"}:t.skipped_needs_decision>0?{variant:"warning",label:"Needs a decision"}:{variant:"success",label:"Synced"}}function cf(t){switch(t){case"completed":return"success";case"failed":return"error";case"uploading":case"processing":case"embedding":default:return"info"}}function df(t){switch(t){case"completed":return"Ready";case"failed":return"Failed";case"uploading":return"Uploading";case"embedding":return"Embedding";case"processing":default:return"Processing"}}function Vr(t){if(!t)return null;const s=vr(t);return s&&s!=="—"?s:null}function uf(t,s){return s==="all"?!0:s==="uploads"?t.kind==="upload":s==="syncs"?t.kind==="sync_batch"||t.kind==="sync_failure":t.kind==="failed_extraction"||t.kind==="brain_review"||t.kind==="tasks"||t.kind==="sync_failure"?!0:t.kind==="sync_batch"?t.batch.skipped_needs_decision>0:t.kind==="upload"&&t.job.status==="failed"}function ua(t){const s=lf({...t});if(t.skipped===0)return s;const r=[s],n=t.skipped_needs_decision;n>0&&r.push(n===1?"1 needs a decision":`${n} need a decision`);const a=t.skipped-n;return a>0&&r.push(t.skipped_up_to_date>=a?`${a} already up to date`:`${a} skipped`),r.join(" · ")}function mf(t){return t.kind==="failed_extraction"||t.kind==="brain_review"||t.kind==="sync_failure"?!0:t.kind==="sync_batch"?t.batch.skipped_needs_decision>0:t.kind==="upload"&&t.job.status==="failed"}function ff(t,s){switch(t.kind){case"failed_extraction":return!0;case"brain_review":return!0;case"sync_failure":return!0;case"sync_batch":return t.batch.skipped_needs_decision>0;case"upload":return t.job.status==="failed"&&!!t.job.jobId&&s;default:return!1}}function hf(t){return t.is_active?!1:t.completed===0&&t.failed===0&&t.skipped===0&&t.skipped_needs_decision===0}function pf(t){const r={...t[0]};r.completed=0,r.failed=0,r.dismissed=0,r.skipped=0,r.skipped_up_to_date=0,r.skipped_needs_decision=0,r.pending=0,r.processing=0,r.total=0,r.is_active=!1,r.current_file_name=null;for(const n of t)r.completed+=n.completed,r.failed+=n.failed,r.dismissed+=n.dismissed,r.skipped+=n.skipped,r.skipped_up_to_date+=n.skipped_up_to_date,r.skipped_needs_decision+=n.skipped_needs_decision,r.pending+=n.pending,r.processing+=n.processing,r.total+=n.total,n.is_active&&(r.is_active=!0,r.current_file_name=r.current_file_name??n.current_file_name);return r}function gf(t){const s=os(t.sortAt,"yyyy-MM-dd","undated");return`${t.batch.connection_id}|${s}`}function xf(t){const s=[],r=new Map;for(const n of t){if(n.kind!=="sync_batch"&&n.kind!=="sync_failure"){s.push({type:"item",item:n});continue}const a=gf(n),o=r.get(a);if(o===void 0){r.set(a,s.length),s.push({type:"group",key:a,sortAt:n.sortAt,batches:[n.batch]});continue}const d=s[o];d.type==="group"&&d.batches.push(n.batch)}return s}function yf(){const{orgId:t,role:s}=Ve(),{canViewQueue:r}=bi(),{toast:n}=ze(),a=ct(),[o,d]=i.useState("all"),[g,c]=i.useState(new Set),[u,h]=i.useState(!1),[x,m]=i.useState(!1),[f,p]=i.useState(null),[v,y]=i.useState(null),[I,M]=i.useState(new Set),{data:k,isLoading:S,isError:T}=mn(t,{limit:25,includeEntityCounts:!1}),{data:O=[],isLoading:w,isError:b}=Xa(),{data:P=[],isLoading:l,isError:$}=ef(),{counts:Q}=Zl(t,s),re=(Q==null?void 0:Q.need_you_total)??0,K=i.useCallback(async C=>{c(A=>new Set(A).add(C));try{const{error:A}=await X.rpc("cancel_embedding_job",{job_id_param:C}
17);if(A)throw A;await a.invalidateQueries({queryKey:["processing-steps",t]})}catch(A){n({title:"Couldn't cancel that upload",description:A instanceof Error?A.message:"Please try again.",variant:"destructive"});return}finally{c(A=>{const B=new Set(A);return B.delete(C),B})}},[t,a,n]),D=i.useCallback(async C=>{if(C.length!==0){h(!0);try{const A=new Date(Date.now()-72e5).toISOString(),{error:B}=await X.from("embedding_jobs").update({archived_at:A,archived_reason:"completed_ok"}).in("job_id",C);if(B)throw B;await a.invalidateQueries({queryKey:["processing-steps",t]})}catch(A){n({title:"Couldn't clear completed uploads",description:A instanceof Error?A.message:"Please try again.",variant:"destructive"})}finally{h(!1)}}},[t,a,n]),E=i.useCallback(async C=>{M(A=>new Set(A).add(C));try{await qo({single_doc_id:C}),await a.invalidateQueries({queryKey:["permanently-failed-extractions",t]})}catch(A){n({title:"Couldn't retry that document",description:A instanceof Error?A.message:"Please try again.",variant:"destructive"})}finally{M(A=>{const B=new Set(A);return B.delete(C),B})}},[t,a,n]),N=i.useMemo(()=>{const C=[];for(const A of k??[])of(A.source_ref)||C.push({kind:"upload",sortAt:A.uploadedAt||A.createdAt||"",job:A});for(const A of O){if(hf(A))continue;const B=!A.is_active&&A.failed>0;C.push({kind:B?"sync_failure":"sync_batch",sortAt:A.finished_at||A.started_at||"",batch:A})}if(r)for(const A of P)C.push({kind:"failed_extraction",sortAt:A.entity_extraction_attempted_at||A.doc_created_at||"",doc:A});return re>0&&C.push({kind:"brain_review",sortAt:new Date().toISOString(),count:re}),C.push({kind:"tasks",sortAt:new Date().toISOString()}),C.sort((A,B)=>(B.sortAt||"").localeCompare(A.sortAt||"")),C},[k,O,P,re,r]),L=i.useMemo(()=>{let C=0;for(const A of N)mf(A)&&ff(A,r)&&(C+=1);return C},[N,r]),U=i.useMemo(()=>N.filter(C=>uf(C,o)),[N,o]),Z=i.useMemo(()=>N.filter(C=>C.kind==="upload"&&C.job.status==="completed"&&!!C.job.jobId).map(C=>C.job.jobId),[N]),le=i.useMemo(()=>U.filter(C=>C.kind==="failed_extraction").length,[U]),De=20,fe=le>De&&!x,ye=i.useMemo(()=>{if(!fe)return U;let C=0;return U.filter(A=>A.kind!=="failed_extraction"?!0:(C+=1,C<=De))},[U,fe]),pe=i.useMemo(()=>xf(ye),[ye]);if((S||w||l)&&N.length===0)return null;if(T&&b)return e.jsx("p",{className:"text-sm",style:{color:"var(--platform-error, #f87171)"},role:"alert",children:"Couldn't load uploads or syncs. Try refresh on the Add page."});const F=$,Y=(C,A)=>e.jsx(q,{asChild:!0,variant:"ghost",size:"xs",onClick:B=>B.stopPropagation(),children:e.jsx(zs,{to:la(C),"aria-label":`Review skipped ${A} files`,children:"Review"})}),ie=C=>{const A=oa(C.provider),B=da(C),te=ca(C.provider),he=f===C.sync_batch_id;return e.jsx(vs,{icon:te?e.jsx(Wr,{sourceKind:null,tags:null,sourceRef:te,size:"sm",colored:!1}):e.jsx(Zt,{className:"h-4 w-4"}),title:A,badgeVariant:B.variant,badgeLabel:B.label,detail:e.jsx(bs,{parts:[Vr(C.finished_at||C.started_at),ua(C),C.is_active?C.current_file_name:null]}),action:C.skipped_needs_decision>0?Y(C.provider,A):void 0,expanded:he,expandLabel:he?`Hide files from this ${A} sync`:`Show files from this ${A} sync`,onToggleExpanded:()=>p(he?null:C.sync_batch_id),expandedContent:he?e.jsx(rf,{batchId:C.sync_batch_id,settingsHref:la(C.provider),settingsLabel:`Open ${A} sync settings`}):null},`sync-${C.sync_batch_id}`)},oe=(C,A,B)=>{const te=pf(B),he=oa(te.provider),ue=da(te),Ae=ca(te.provider),Ce=v===C,xe=os(A,"MMM d",""),$e=xe?`${he} · ${xe}`:he;return e.jsx(vs,{icon:Ae?e.jsx(Wr,{sourceKind:null,tags:null,sourceRef:Ae,size:"sm",colored:!1}):e.jsx(Zt,{className:"h-4 w-4"}),title:$e,badgeVariant:ue.variant,badgeLabel:ue.label,detail:e.jsx(bs,{parts:[`${B.length} runs`,ua(te)]}),action:te.skipped_needs_decision>0?Y(te.provider,he):void 0,expanded:Ce,expandLabel:Ce?`Hide the ${B.length} ${he} runs from ${xe||"this day"}`:`Show the ${B.length} ${he} runs from ${xe||"this day"}`,onToggleExpanded:()=>y(Ce?null:C),expandedContent:Ce?e.jsx("ul",{className:"divide-y divide-white/10",children:B.map(se=>ie(se))}):null},`sync-group-${C}`)};return e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-1 border-b border-[var(--white-8)]",role:"tablist","aria-label":"Activity filters",children:[{id:"all",label:"All"},{id:"uploads",label:"Uploads"},{id:"syncs",label:"Syncs"},{id:"needs",label:"Needs attention",count:L}].map(C=>e.jsxs(q,{type:"button",variant:"subtab",size:"sm",role:"tab","aria-selected":o===C.id,"data-active":o===C.id,onClick:()=>d(C.id),children:[C.label,C.count!==void 0&&C.count>0?e.jsx("span",{className:"ml-1.5 inline-flex h-[18px] min-w-[18px] items-center justify-center rounded-full bg-white/[0.10] px-1.5 text-[10px] leading-none text-white/55","aria-hidden":!0,
17children:C.count}):null]},C.id))}),F&&e.jsx("p",{className:"text-sm",style:{color:"var(--platform-error, #f87171)"},role:"alert",children:"Couldn't load permanently-failed extractions."}),o==="uploads"&&Z.length>0&&e.jsx("div",{className:"flex justify-end",children:e.jsx(q,{type:"button",variant:"ghost",size:"xs",disabled:u,onClick:()=>void D(Z),children:u?"Clearing…":"Clear completed"})}),U.length===0&&!F?e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-muted)"},children:o==="uploads"?"No recent uploads. Files you add will show up here while they process.":o==="syncs"?"Connected sources will list their last syncs here.":o==="needs"?"Nothing needs attention right now.":"Nothing in progress. New uploads and syncs will appear here."}):e.jsx("ul",{className:"-mx-6 divide-y divide-white/10 border-y border-white/10",children:pe.map(C=>{if(C.type==="group")return C.batches.length===1?ie(C.batches[0]):oe(C.key,C.sortAt,C.batches);const{item:A}=C;if(A.kind==="upload"){const{job:B}=A,te=!!(B.jobId&&B.status!=="completed"&&r),he=B.status==="completed"&&B.documentId?`/library/${B.documentId}`:void 0,ue=B.title||"Untitled";return e.jsx(vs,{icon:e.jsx(Ol,{className:"h-4 w-4"}),title:ue,badgeVariant:cf(B.status),badgeLabel:df(B.status),detail:e.jsx(bs,{parts:[Vr(B.uploadedAt||B.createdAt),B.status==="failed"?B.error:null]}),to:he,linkLabel:`Open ${ue}`,action:te&&B.jobId?e.jsx(q,{type:"button",variant:"ghost",size:"icon-xs",loading:g.has(B.jobId),"aria-label":`Cancel upload ${ue}`,onClick:Ae=>{Ae.stopPropagation(),B.jobId&&K(B.jobId)},children:e.jsx(at,{className:"h-3.5 w-3.5","aria-hidden":!0})}):void 0},`upload-${B.id}`)}if(A.kind==="failed_extraction"){const{doc:B}=A,te=B.title||"Untitled";return e.jsx(vs,{icon:e.jsx(Et,{className:"h-4 w-4"}),title:te,badgeVariant:"error",badgeLabel:"Extraction failed",detail:e.jsx(bs,{parts:[Vr(B.entity_extraction_attempted_at),B.entity_extraction_error]}),to:`/library/${B.doc_id}`,linkLabel:`Open ${te}`,action:e.jsx(q,{type:"button",variant:"ghost",size:"xs",disabled:I.has(B.doc_id),"aria-label":`Retry extraction for ${te}`,onClick:he=>{he.stopPropagation(),he.preventDefault(),E(B.doc_id)},children:I.has(B.doc_id)?"Retrying…":"Retry"})},`failed-${B.doc_id}`)}if(A.kind==="brain_review"){const B=A.count===1?"1 item needs your review":`${A.count} items need your review`;return e.jsx(vs,{icon:e.jsx($l,{className:"h-4 w-4"}),title:B,badgeVariant:"warning",badgeLabel:"Review",detail:e.jsx(bs,{parts:["Waiting on a decision"]}),to:qt.BRAIN,linkLabel:"Open Brain Center"},"brain-review")}return e.jsx(vs,{icon:e.jsx(Ml,{className:"h-4 w-4"}),title:"Actions waiting on you",badgeVariant:"neutral",badgeLabel:"Tasks",detail:e.jsx(bs,{parts:["Work you handed over"]}),to:qt.TASKS,linkLabel:"Open Tasks"},"tasks")})}),fe&&e.jsx("div",{className:"-mt-2 flex justify-center",children:e.jsx(q,{type:"button",variant:"ghost",size:"xs",onClick:()=>m(!0),children:`Show all ${le}`})})]})}function vf(t,s){const r=!!(t!=null&&t.length),n=!!(s!=null&&s.length);if(!r&&!n)return{status:"idle",count:null};const a=(t??[]).filter(h=>h.status==="processing"||h.status==="embedding"||h.status==="uploading").length,o=(t??[]).filter(h=>h.status==="failed").length,d=(s??[]).filter(h=>h.is_active).length,g=(s??[]).filter(h=>!h.is_active).reduce((h,x)=>h+x.failed,0),c=a+d;if(c>0)return{status:"active",count:c};const u=o+g;return u>0?{status:"error",count:u}:{status:"success",count:null}}function bf(t,s,r,n){if(s==="connected"&&n)return Rt;if(t===Rt&&n)return Rt;const a=sn(t);return a&&r?a:r?"file":Rt}function wf({onCreateText:t,onUploadComplete:s}){wr("Add");const{orgId:r}=Ve(),[n,a]=Es(),{canViewQueue:o}=bi(),{canCreateContent:d}=Sa(),{canConnect:g,isLoading:c}=ja(),u=d,h=g,x=n.get(Sn),m=fu(x)?x:null,f=bf(n.get("tab"),n.get("mode"),u,h),p=n.get(Nn),v=o&&(n.get("activity")==="open"||p!==null);i.useEffect(()=>{const l=n.get("mode");l&&a($=>{const Q=new URLSearchParams($);return Q.delete("mode"),l==="connected"&&h?Q.set("tab",Rt):!Q.get("tab")&&u&&Q.set("tab","file"),Q},{replace:!0})},[n,a,h,u]);const{data:y,isLoading:I,isError:M}=mn(r,{limit:25,includeEntityCounts:!1}),{data:k}=Xa(),S=i.useMemo(()=>vf(y,k),[y,k]),T=Array.isArray(y)&&y.length>0,O=i.useCallback((l,$)=>{a(Q=>{const re=new URLSearchParams(Q);return $==null||$===""?re.delete(l):re.set(l,$),re},{replace:!0})},[a]);i.useEffect(()=>{p!==null&&a(l=>{const $=new URLSearchParams(l);return $.delete(Nn),o&&$.set("activity","open"),$},{replace:!0})},[p,o,a]),i.useEffect(()=>{x===null||m!==null||O(Sn,null)},[x,m,O]),i.useEffect(()=>{!m||!h||n.get("tab")||O("tab",Rt)},[m,h,n,O]);const w=i.useCallback(()=>{O("activity","open")},[O]),b=i.useCallback(()=>{O("activity",null)},[O]);if(n.get("tab")===Go)return e.jsx(tr,{to:qt.TEAM_ONBOARDING,replace:!0});if(!c&&!u&&!h)return e.jsx(tr,{to:qt.HOME,replace:!0});const P=f===Rt;return e.jsx(Na,{children:e.jsxs("div",{className:Ue(Ut.platformPage,"flex flex-col gap-8"),children:[e.jsxs("div",{className:"flex flex-col gap-5",children:[e.jsx(rn,{title:"Add",subtitle:"How do you want to get knowledge in?",titleIcon:e.jsx(_r,{className:"h-6 w-6 text-[var(--gold)]","aria-hidden":!0}),helpHref:"/support/add",rightContent:e.jsx("div",{className:"flex flex-wrap items-center justify-end gap-2",children:o?e.jsx(Wo,{label:"Activity",prominence:"secondary",status:M?"error":S.status,count:M?null:S.count,onClick:w,"aria-expanded":v}):null})}),!c&&u&&e.jsx(Wa,{showSyncMethod:h,showManualMethods:u})]}),e.jsx("div",{className:"border-t border-[var(--gold-border)]"}),c?e.jsx("div",{className:"flex min-h-[200px] items-center justify-center text-sm",style:{color:"var(--platform-text-muted)"},children:"Loading…"}):u?e.jsx(Zm,{embedded:!0,hideMethodChips:!0,showSyncMethod:h,onCreateText:t,onUploadComplete:s}):P&&h?e.jsx(hi,{children:e.jsx(fi,{embedded:!0})}):e.jsx(tr,{to:qt.UPLOAD_CONNECTED,replace:!0}),o&&e.jsx(Yo,{isOpen:v,onClose:b,title:"Activity",isLoading:!!(I&&!T&&!M),emptyState:M?e.jsx("p",{className:"text-sm",style:{color:"var(--platform-error, #f87171)"},role:"alert",children:"Couldn't load upload status. Try refresh."}):e.jsx("p",{className:"text-sm",style:{color:"var(--platform-text-muted)"},children:"Nothing in progress. New uploads and syncs will appear here."}),className:"sm:max-w-lg",children:M?null:e.jsx(yf,{})})]})})}const us={all:["hierarchical-graph"],level0:t=>[...us.all,"level0",t],level1:(t,s)=>[...us.all,"level1",t,s],level2:(t,s)=>[...us.all,"level2",t,s],level3:(t,s)=>[...us.all,"level3",t,s]};function _f(){const t=ct(),s=i.useCallback(async()=>{await Promise.all([t.invalidateQueries({queryKey:Xs.all}),t.invalidateQueries({queryKey:us.all})])},[t]),r=i.useCallback(async a=>{await Promise.all([t.invalidateQueries({queryKey:Xs.entities(a)}),t.invalidateQueries({queryKey:us.all})])},[t]),n=i.useCallback(async a=>{await Promise.all([t.invalidateQueries({queryKey:Xs.org(a)}),t.invalidateQueries({queryKey:Xs.entities(a)}),t.invalidateQueries({queryKey:us.level0(a)})])},[t]);
17return{invalidateAllGraphCaches:s,invalidateEntityCaches:r,invalidateOrgGraphCaches:n}}const jf={file:"file",url:"url",text:"text",voice:"voice",ai:"ai-create"},Sf={idle:null,file:"file",url:"url",text:"text",voice:"voice","ai-create":"ai"};function wh(){wr("Add Content");const t=ct(),{toast:s}=ze(),{orgId:r,org:n}=Ve(),a=(n==null?void 0:n.org_type)===Oe.BUSINESS||(n==null?void 0:n.org_type)===Oe.INTERNAL,{mode:o}=Wi(),d=Cs(),{invalidateAllGraphCaches:g}=_f(),[c]=Es();c.get("context")==="gap"&&(c.get("gap_id"),c.get("topic"));const[u,h]=i.useState(!1),[x,m]=i.useState(!1);i.useCallback((v,y)=>{m(y);const I=Sf[v];I!==(o||null)&&(I?d(`/upload/${I}`,{replace:!0}):d("/upload",{replace:!0}))},[d,o]);const f=i.useCallback(async(v,y,I,M,k)=>{var S;try{const{data:{user:T}}=await X.auth.getUser();if(!T)throw new Error("User not authenticated");const{data:O}=await X.from("org_members").select("org_id").eq("user_id",T.id).order("created_at",{ascending:!1}).limit(1).maybeSingle(),w=(O==null?void 0:O.org_id)??r,b=await Vo({title:v.trim(),content:y,tags:I,org_id:w??void 0,skip_duplicate_check:k==null?void 0:k.skip_duplicate_check,department_id:k==null?void 0:k.department_id});if(!(b!=null&&b.success))throw new Error("Failed to start review");if(b.action_required==="update_or_version")return{action_required:b.action_required,existing_doc_id:b.existing_doc_id??"",existing_title:b.existing_title??"Unknown"};(S=b.pii_notification)!=null&&S.detected&&s({title:"PII Auto-Redacted",description:b.pii_notification.message||"PII detected and will be auto-redacted before AI processing."});let P=null;try{const l=sessionStorage.getItem("pendingResourceRequestId");if(l){const $=JSON.parse(l);$.id&&$.ts&&Date.now()-$.ts<6e5?P=$.id:sessionStorage.removeItem("pendingResourceRequestId")}}catch{P=sessionStorage.getItem("pendingResourceRequestId")}if(P&&b.doc_id)try{const{data:l,error:$}=await X.from("resource_requests").select("user_id, org_id, linked_resource_id").eq("id",P).single();if(!$&&l&&!l.linked_resource_id){const Q=new Date().toISOString(),{error:re}=await X.from("resource_requests").update({linked_resource_id:b.doc_id,linked_resource_title:v.trim()||"Untitled",status:ma.COMPLETED,resolution_type:"created_new",fulfilled_by:T.id,fulfilled_at:Q,resolved_at:Q,resolved_by:T.id}).eq("id",P);re||(await X.from("resource_request_notifications").insert({request_id:P,user_id:l.user_id,notification_type:"resource_linked",message:`Your requested resource "${v.trim()||"Untitled"}" has been created!`}),t.invalidateQueries({queryKey:["admin-resource-requests"]}),t.invalidateQueries({queryKey:["resource-requests"]}),t.invalidateQueries({queryKey:["notifications"]}))}sessionStorage.removeItem("pendingResourceRequestId")}catch(l){W("AddPage",l,"Error auto-fulfilling resource request:"),sessionStorage.removeItem("pendingResourceRequestId")}if(M){const l=wa.PENDING_REVIEW_SIGNALING&&a&&!(k!=null&&k.department_id);s({title:l?"Saved for review":"Document published",description:l?"Saved. Awaiting review: an admin needs to assign an access group before it's answerable.":"Your document is being indexed.",variant:"success"}),t.invalidateQueries({queryKey:["processing-steps",r]}),g()}else{const l=b.job_id??"";d(Ko(l))}}catch(T){const O=T instanceof Error?T.message:"Failed to create";s({title:"Error",description:O,variant:"destructive"})}},[r,a,t,s,g,d]),p=i.useCallback(()=>{m(!0),Ls(t,["documents"]),g(),t.refetchQueries({queryKey:["processing-steps",r],type:"active"})},[t,r,g]);i.useCallback(()=>{d("/upload")},[d]);{if(o&&jf[o]){const v=o==="ai"?"ai":o==="text"?"write":o,y=new URLSearchParams(c);return y.set("tab",v),y.delete("mode"),e.jsx(tr,{to:`/upload?${y.toString()}`,replace:!0})}return e.jsx(wf,{onCreateText:f,onUploadComplete:p})}}export{wh as AddPage,wh as default};

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.