1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AssadVoiceMode-CT4anZCz.js","assets/rolldown-runtime-C_JJxWoe.js","assets/vendor-react-qjw5lwXl.js","assets/vendor-misc-Ccq730ZN.js","assets/utils-B1g7HtwT.js","assets/vendor-ui-DQ8u3dBU.js","assets/vendor-supabase-DbAiLHYG.js","assets/vendor-router-BqzTHgxF.js","assets/logger-CMpUf36D.js","assets/sentry-llrRemFk.js","assets/vendor-shared-C87iPVW7.js","assets/index-BlCwc86_.js","assets/index-cFFPcZXa.css","assets/translate-COFeEXZN.js","assets/i18n-CmOgFzpK.js","assets/client-D25M3Qae.js","assets/useAuth-DRxi8jEl.js","assets/vendor-query-fsW8-X5n.js","assets/perfLogger-Cp6mKDel.js","assets/supabaseRuntime-D7w8nJ6G.js","assets/mfaSession-DnKhmWUD.js","assets/signOutCleanup-jOW4BmYA.js","assets/useModuleActive-DktO8x8-.js","assets/types-BrLLI40R.js","assets/useIsAdmin-zJmvUefy.js","assets/realtimeTopic-CQj8Z44v.js","assets/TemplateGate-CI_r7N7v.js","assets/dialog-DpV-dmMx.js","assets/memberAccess-f1vqoUHo.js","assets/useProjectRealtime-r-4JaSZL.js","assets/safeStorage-CkSQ1N5s.js","assets/skeleton-B7QcexiN.js","assets/planningModules-DqO8a9Q0.js","assets/vendor-motion-BuDjhNKC.js","assets/AssistantAvatar-BqwUzypD.js","assets/CreditPaywallContext-j8A0V41B.js","assets/edgeFunctionError-ugSmy7e6.js","assets/badge-Ch3H9HJ9.js","assets/stripeCheckout-CuIrA00b.js","assets/TopUpDialog-mki8BWhs.js","assets/useCredits-CZlkwBve.js","assets/walletEvents-DqxpHsBo.js","assets/geminiService-bhQyx-Vo.js","assets/boardStatuses-yTdmQs94.js","assets/restrictedTasks-Cktg6ISt.js","assets/permissionErrors-CkVjt2Mv.js","assets/taskAssignee-B0vlqQ-i.js","assets/vendor-genai-DEt3noka.js","assets/html2canvas-BZeoWjzY.js","assets/ModuleTransitionCoach-DjsuQ0tH.js","assets/scroll-area-CQq5Os3F.js","assets/checkbox-ClSKPdGj.js","assets/CoachFeedbackFloatingButton-DA-jKGYp.js","assets/onboarding-Byk_kXSF.js","assets/input-BgeHxvhI.js","assets/label-Dv3bsvTJ.js","assets/PortfolioOnboardingDialog-DIQVtTuK.js","assets/alert-dialog-BEtM7j-2.js","assets/templates-B8_eOZ_i.js","assets/KeyboardShortcutHelp-CeElW83u.js","assets/PhaseTransitionGuide-oc-e1VAh.js","assets/CalendarReminderRunner-C1wV1H7M.js","assets/TaskManager-BHlxdUWP.js","assets/vendor-recharts-DjXNGXPC.js","assets/vendor-lodash-DKbyThM8.js","assets/productRoadmap-DB63gepM.js","assets/progress-CeCLa2C3.js","assets/command-QZ6PAF4y.js","assets/use-mobile-Dgl_HMe_.js","assets/textarea-DE4b57Ep.js","assets/teamService-CbVCHSNd.js","assets/auditService-DBdTVH-D.js","assets/profileService-DKdR-Ui2.js","assets/select-ENO3qDQ_.js","assets/switch-pS5f8ffW.js","assets/popover-DLiD3cKU.js","assets/useConfirm-CjPHyDWY.js","assets/FullScreenButton-BVVqSYXJ.js","assets/dropdown-menu-f-nwqdC4.js","assets/module-DkiVbzke.js","assets/tabs-CH9QfQl9.js","assets/useFullScreen-C2Cy40di.js","assets/collapsible-CVyIOnJL.js","assets/csv-BoyKr9PB.js","assets/radio-group-aIo0Z3pi.js","assets/avatar-DJz8QMKo.js","assets/avatarUtils-DBrBLlns.js","assets/useWatchlist-BOHdmx6S.js","assets/context-menu-BJOqfgZO.js","assets/StarButton-Cq79816D.js","assets/VoiceInputButton-CqU16YmN.js","assets/vendor-dnd-DSzwgjWa.js","assets/statusColor-DHrkmeKK.js","assets/MentionedInBadge-ChKmYQCI.js","assets/linkingService-DZMXdrW_.js","assets/useSmartLinks-CU8wKOMH.js","assets/useNotifications-Dbu7m1IF.js","assets/krCheckIns-BxLmgtdK.js","assets/ItemVisibilityControl-CXg8VEJZ.js","assets/Notes-D-q6uGpm.js","assets/useProjectTasks-BPONaY1o.js","assets/db-eg6I0BSU.js","assets/transcriptUtils-CJq2f9Ua.js","assets/sanitize-C5zroJ3P.js","assets/purify.es-DWnPTElA.js","assets/useSignedStorageUrl-WJBZuCyS.js","assets/storageRef-C7pluCka.js","assets/useProjectOKRs-Ch2lPK_B.js","assets/hover-card-ID4xsrSs.js","assets/useOnlineStatus-CyN683AC.js","assets/supabasePaging-VBg81_CE.js","assets/documentSaveQueue-DHxipGnD.js","assets/realtimeRooms-Bft9FVH7.js","assets/BlockEditor-DqKy9qRm.js","assets/lucide-shims-BiVGJP7t.js","assets/SecureImage-CP94HNsK.js","assets/SmartEmptyState-Bg-JS3t1.js","assets/OKRs-DMr0qGGK.js","assets/slider-CxqLGaj1.js","assets/KRNumberInput-BdE4F0_k.js","assets/calendar-M4mx8mBi.js","assets/ModuleInsightBannerConnected-BnahoInL.js","assets/ai-DcHb3ofo.js","assets/AIPromptViewer-BVxRaCKy.js","assets/crmStageKinds-BHeIxMKH.js","assets/financeActuals-CZGc_GHR.js","assets/usePersistentSave-D4Hg6m_z.js","assets/okrQuarters-Cm-dLysZ.js","assets/OKRReminderSettings-vdm84rn7.js","assets/Ideation-BUm_r9kq.js","assets/useAnalyticsTracking-2RyEF_r3.js","assets/analyticsService-vkkZwRJL.js","assets/useAILimit-DYKAV3Q6.js","assets/PlanningModuleToolbar-B3unvhXB.js","assets/activityService-mmltFkYP.js","assets/ModuleGenerationLoading-BAEAQ0TJ.js","assets/QuickTaskButton-C2p2f3ZQ.js","assets/MarketResearch-guA8_3Vn.js","assets/accordion-CvEhIn10.js","assets/moduleNav
1-u1_aBYjC.js","assets/table-CRmgsOZS.js","assets/useRegenerateOnImpact-DuMDG_DA.js","assets/DownstreamImpactPanel-C1czpLw1.js","assets/useReplaceConfirm-DXwQKVac.js","assets/TabExplanation-ByLIXBf1.js","assets/SortableItem-DovaPPpP.js","assets/projectUpdates-CGbHSblO.js","assets/BusinessStrategy-muSX_fjS.js","assets/ProductSpecs-Druyt6IX.js","assets/regenerationMerge-DEGWnzh6.js","assets/productNormalize-CbtnyLQh.js","assets/MarketingHub-vFLFp5qB.js","assets/Financials-CZAjJWoh.js","assets/FinanceAssumptionsPanel-fbKWNaRz.js","assets/FinanceDashboard-LZoEO94b.js","assets/financeMetrics-Blvl-X_-.js","assets/Pricing-RubEeSeK.js","assets/Investors-nzai0sul.js","assets/pulseHRTemplate-BXStJlJb.js","assets/hr-Oc1eOcaa.js","assets/separator-dahJchDf.js","assets/dataRoomService-BUvGoikA.js","assets/CustomerCRM-AbN04CGi.js","assets/crmService-CAWjHsF5.js","assets/crmPipelineService-Bw-EqfIx.js","assets/Mail-Cfml36Ms.js","assets/useMyMailboxes-CHoc3WNI.js","assets/DemoMail-CiJtJrC8.js","assets/Legal-NfJRDmud.js","assets/vendor-markdown-Cb478xTs.js","assets/useAIWithCredits-DkD1Y-dO.js","assets/useEmailVerification-C8NiVyLT.js","assets/TeamStructure-B3U5RgK3.js","assets/alert-FyFtTORW.js","assets/Fundraising-DRtg2UOs.js","assets/PitchDeck-ZRDlSb5c.js","assets/vendor-forms-BwyNV8T-.js","assets/AICoach-DuU_tzGo.js","assets/TrustedMarkdownImage-CfQECY4j.js","assets/HR-DWbViZx9.js","assets/useHREmployees-DrLw44IM.js","assets/MyHRView-zLoE8gbP.js","assets/driveService-Ch4FhNeK.js","assets/RiskAnalysis-WOucsEBe.js","assets/CustomerDiscovery-svFccKCE.js","assets/WhiteboardResponsive-BAAwuR-U.js","assets/MeetingNotes-C14y3WaX.js","assets/CalendarModule-Bwfq9Fc_.js","assets/useCalendarConnection-C250vwOA.js","assets/functionUrl-CmAxewto.js","assets/GitHubModule-eaY9fN8e.js","assets/githubService-HlTQTKYw.js","assets/useGitHub-DMXoV9nf.js","assets/Drive--pP69fp1.js","assets/PixelOffice-BJtj-uXS.js","assets/TeamManagement-uXTLQuGA.js","assets/MemberAccessDialog-BSpJnINc.js","assets/PendingInvites-C-S_PEXV.js","assets/DeleteProjectDialog-DibEP9QF.js","assets/NewsCenter-DUHrXx-p.js","assets/MobileBottomNav-SSFLkrx_.js","assets/MobileModuleDrawer-BCb4SXWZ.js","assets/Advertising-BeBB6RXk.js","assets/WebsiteBuilder-C1kDgrar.js","assets/CompetitorWarRoom-BlaUHkUu.js","assets/MobileMenu-DmwKIZZa.js","assets/BusinessPlanDialog-BpCbw_eJ.js","assets/brandBookExport-DqSHjlkW.js","assets/migration-C4BSyUBu.js","assets/jszip.min-DokFpiT6.js","assets/whiteboardImportMapping-BC01xjc2.js","assets/CommunicationBoard-D2hN2uJF.js","assets/useTeamCalls-DIdYKLdG.js","assets/TeamCallsHost-CN9V1qle.js","assets/ImageLightbox-B8rsh4Jy.js","assets/ProjectSettingsDialog-BsenHkLa.js","assets/useWallet-DV-rCWR_.js","assets/CreditTopUpPacks-BZGBUnz2.js","assets/dashboard-CNA0CMUw.js","assets/TodayView-CZ3P9PyR.js","assets/TodayCockpitCard-_pcftHyF.js","assets/GlobalCommandPalette-DV-PAbM0.js","assets/TeamPulse-C2KV1cGn.js","assets/FloatingQuickActions-BkTGoXCf.js","assets/PhaseContextBanner-BQt1gMpW.js","assets/ModuleBreadcrumb-BjAFlFxH.js","assets/AssistantTopBarButton-xlywZ6Gs.js","assets/PeekPanel-CqJY5wxB.js","assets/PinStrip-mBiEJkEn.js","assets/NextActionBanner-Dqbwy5oF.js"])))=>i.map(i=>d[i]); 2import{o as e,r as t}from"./rolldown-runtime-C_JJxWoe.js";import{a as r,n as a}from"./vendor-react-qjw5lwXl.js";import{An as s,Bo as n,Bt as i,Cr as o,Cs as l,Ea as c,Fa as d,Fr as u,G as m,Ga as p,Ii as h,It as f,K as g,Kn as x,Ko as _,Ks as b,Kt as j,Lr as v,M as y,Mn as w,Mo as N,Nn as k,Nr as S,Ns as I,Nt as C,Os as E,Pi as T,Po as A,Q as D,Qo as O,Qt as R,Sa as M,Tn as P,Ua as L,Va as U,Vt as $,Wi as F,Wo as W,Xo as K,Y as H,Yr as q,Z as z,Zr as V,_o as B,_t as G,aa as Y,at as J,br as Q,c as Z,ca as X,cn as ee,cs as te,ei as re,eo as ae,fn as se,fo as ne,ft as ie,go as oe,ht as le,ii as ce,in as de,ir as ue,it as me,j as pe,ji as he,jr as fe,l as ge,la as xe,mt as _e,ni as be,nn as je,oa as ve,oo as ye,or as we,q as Ne,qt as ke,ro as Se,rr as Ie,si as Ce,tr as Ee,ts as Te,tt as Ae,ui as De,ur as Oe,us as Re,vo as Me,vt as Pe,wt as Le,yo as Ue,ys as $e,zo as Fe,zs as We}from"./vendor-misc-Ccq730ZN.js";import{n as Ke,t as He}from"./utils-B1g7HtwT.js";import{d as qe,o as ze,s as Ve,u as Be}from"./vendor-router-BqzTHgxF.js";import{t as Ge}from"./logger-CMpUf36D.js";import{A as Ye,C as Je,F as Qe,L as Ze,M as Xe,N as et,P as tt,T as rt,d as at,g as st,m as nt,t as it,u as ot,w as lt}from"./index-BlCwc86_.js";import{n as ct,t as dt}from"./translate-COFeEXZN.js";import{r as ut}from"./i18n-CmOgFzpK.js";import{a as mt,i as pt,n as ht,o as ft,r as gt,t as xt}from"./dialog-DpV-dmMx.js";import{t as _t}from"./scroll-area-CQq5Os3F.js";import{n as bt,t as jt}from"./types-BrLLI40R.js";import{a as vt,c as yt,i as wt,n as Nt,o as kt,r as St,s as It,t as Ct}from"./alert-dialog-BEtM7j-2.js";import{t as Et}from"./input-BgeHxvhI.js";import{a as Tt,n as At}from"./vendor-query-fsW8-X5n.js";import{i as Dt,o as Ot,r as Rt,s as Mt,t as Pt}from"./command-QZ6PAF4y.js";import{t as Lt}from"./client-D25M3Qae.js";import{t as Ut}from"./perfLogger-Cp6mKDel.js";import{n as $t}from"./useAuth-DRxi8jEl.js";import{t as Ft}from"./supabaseRuntime-D7w8nJ6G.js";import{a as Wt}from"./signOutCleanup-jOW4BmYA.js";import{t as Kt}from"./use-mobile-Dgl_HMe_.js";import{a as Ht,d as qt,i as zt,l as Vt,o as Bt,u as Gt}from"./useModuleActive-DktO8x8-.js";import{t as Yt}from"./useIsAdmin-zJmvUefy.js";import{t as Jt}
2from"./realtimeTopic-CQj8Z44v.js";import{t as Qt}from"./useProjectRealtime-r-4JaSZL.js";import{$ as Zt,B as Xt,C as er,G as tr,H as rr,I as ar,K as sr,Q as nr,R as ir,S as or,V as lr,X as cr,Y as dr,_ as ur,a as mr,et as pr,i as hr,it as fr,n as gr,nt as xr,q as _r,r as br,rt as jr,s as vr,t as yr,tt as wr,v as Nr,w as kr,x as Sr,y as Ir,z as Cr}from"./TemplateGate-CI_r7N7v.js";import{a as Er,o as Tr,s as Ar}from"./vendor-motion-BuDjhNKC.js";import{n as Dr}from"./useTutorial-BblN4tW5.js";import{t as Or}from"./AssistantAvatar-BqwUzypD.js";import{n as Rr}from"./pulseHRTemplate-BXStJlJb.js";import{t as Mr}from"./edgeFunctionError-ugSmy7e6.js";import{t as Pr}from"./badge-Ch3H9HJ9.js";import{o as Lr}from"./stripeCheckout-CuIrA00b.js";import{n as Ur}from"./CreditPaywallContext-j8A0V41B.js";import{t as $r}from"./TopUpDialog-mki8BWhs.js";import{t as Fr}from"./walletEvents-DqxpHsBo.js";import{t as Wr}from"./useCredits-CZlkwBve.js";import{a as Kr}from"./ai-DcHb3ofo.js";import{t as Hr}from"./textarea-DE4b57Ep.js";import{r as qr,t as zr}from"./safeStorage-CkSQ1N5s.js";import{n as Vr}from"./vendor-markdown-Cb478xTs.js";import{t as Br}from"./TrustedMarkdownImage-CfQECY4j.js";import{c as Gr}from"./teamService-CbVCHSNd.js";import{n as Yr,o as Jr,r as Qr,s as Zr}from"./permissionErrors-CkVjt2Mv.js";import{a as Xr,i as ea,n as ta,r as ra,t as aa}from"./select-ENO3qDQ_.js";import{t as sa}from"./switch-pS5f8ffW.js";import{t as na}from"./label-Dv3bsvTJ.js";import{t as ia}from"./CreditTopUpPacks-BZGBUnz2.js";import{i as oa,r as la,t as ca}from"./popover-DLiD3cKU.js";import{n as da}from"./useConfirm-CjPHyDWY.js";import{t as ua}from"./functionUrl-CmAxewto.js";import{t as ma}from"./skeleton-B7QcexiN.js";import{a as pa,i as ha,l as fa,n as ga,r as xa,t as _a}from"./dropdown-menu-f-nwqdC4.js";import{i as ba,n as ja,r as va,t as ya}from"./tabs-CH9QfQl9.js";import{n as wa,r as Na,t as ka}from"./useProjectTasks-BPONaY1o.js";import{d as Sa,l as Ia}from"./boardStatuses-yTdmQs94.js";import{$ as Ca,C as Ea,D as Ta,E as Aa,F as Da,G as Oa,H as Ra,L as Ma,M as Pa,N as La,Q as Ua,R as $a,T as Fa,U as Wa,V as Ka,Y as Ha,a as qa,at as za,c as Va,g as Ba,m as Ga,o as Ya,ot as Ja,r as Qa,rt as Za,t as Xa,v as es,z as ts}from"./restrictedTasks-Cktg6ISt.js";import{_ as rs,a as as,b as ss,c as ns,f as is,g as os,m as ls,n as cs,o as ds,p as us,r as ms,s as ps,t as hs}from"./db-eg6I0BSU.js";import{i as fs,t as gs}from"./useAnalyticsTracking-2RyEF_r3.js";import{n as xs,t as _s}from"./radio-group-aIo0Z3pi.js";import{t as bs}from"./authRedirect-C8XobdIq.js";import{n as js,r as vs,t as ys}from"./avatar-DJz8QMKo.js";import{t as ws}from"./avatarUtils-DBrBLlns.js";import"./LowCreditsWarning-DCf-YDz0.js";import{t as Ns}from"./useWatchlist-BOHdmx6S.js";import{t as ks}from"./TodayCockpitCard-_pcftHyF.js";import{t as Ss}from"./useEmailVerification-C8NiVyLT.js";import{r as Is,t as Cs}from"./realtimeRooms-Bft9FVH7.js";import{t as Es}from"./VoiceInputButton-CqU16YmN.js";import{t as Ts}from"./calendar-M4mx8mBi.js";import{d as As}from"./dataRoomService-BUvGoikA.js";import{t as Ds}from"./planningModules-DqO8a9Q0.js";import{t as Os}from"./activityService-mmltFkYP.js";import{A as Rs,M as Ms,O as Ps,S as Ls,_ as Us,a as $s,b as Fs,c as Ws,f as Ks,g as Hs,i as qs,k as zs,l as Vs,m as Bs,o as Gs,u as Ys,v as Js,x as Qs}from"./crmService-CAWjHsF5.js";import{n as Zs,t as Xs}from"./projectUpdates-CGbHSblO.js";import{t as en}from"./usePersistentSave-D4Hg6m_z.js";import{consumePreloadedProjects as tn}from"./projectsPreloader-AnHV0K5B.js";import{t as rn}from"./LanguageToggle-B42vkchA.js";import{a as an,c as sn,d as nn,f as on,i as ln,l as cn,n as dn,o as un,r as mn,t as pn,u as hn}from"./syncService-Ckg_nIm2.js";var fn=e(r(),1),gn={admin:4,editor:3,member:2,viewer:1},xn=new Set(["admin","editor","member","viewer"]);async function _n(e,t){const[r,a]=await Promise.all([Lt.from("projects").select("user_id").eq("id",e).maybeSingle(),Lt.from("project_members").select("role, accepted_at").eq("project_id",e).eq("user_id",t)]);if(r.error)throw r.error;if(a.error)throw a.error;return function(e,t,r){if(!e)return null;if(t&&t===e)return"owner";let a=null;for(const s of r??[])s?.accepted_at&&s.role&&xn.has(s.role)&&(null===a||(gn[s.role]??0)>(gn[a]??0))&&(a=s.role);return a}(t,r.data?.user_id??null,a.data??[])}function bn(e){const{user:t}=$t(),r=t?.id??null,a=Tt(),s=!!e&&!!r&&Ft(),n=((e,t)=>["project-role",e??null,t??null])(e,r),{data:i,isLoading:o,error:l}=At({queryKey:n,queryFn:()=>_n(e,r),enabled:s,staleTime:6e4});(0,fn.useEffect)(()=>{l&&Ge.error("Failed to resolve the project role",l,{projectId:e})},[l,e]),Qt(s?e:null,"project_members",{onChange:()=>{a.invalidateQueries({queryKey:["project-role",e??null]})}},[a,e]);const c=s?i??null:null,d=s&&o;return(0,fn.useEffect)(()=>{e&&!d&&Zr(e,"viewer"===c)},[e,c,d]),(0,fn.useMemo)(()=>function(e,t=!1){const r="viewer"===e;return{role:e,loading:t,isOwner:"owner"===e,isViewer:r,canEdit:!r,canManageProject:"owner"===e||"admin"===e}}(c,d),[c,d])}var jn=a();function vn({className:e,compact:t=!1}){const{t:r}=at(),a=r("permissions.view_only_badge"),s=r("permissions.view_only_tooltip");return(0,jn.jsxs)(tt,{children:[(0,jn.jsx)(Ze,{asChild:!0,children:(0,jn.jsxs)("button",{type:"button",title:s,"aria-label":t?a:void 0,"data-testid":"view-only-badge",onClick:()=>Jr(),className:He("inline-flex shrink-0 items-center gap-1 rounded-full border border-border bg-muted px-2 py-0.5 text-xs font-medium text-muted-foreground","focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",e),children:[(0,jn.jsx)(U,{className:"h-3 w-3","aria-hidden":!0}),(0,jn.jsx)("span",{className:t?"hidden sm:inline":void 0,children:a})]})}),(0,jn.jsx)(Qe,{side:"bottom",className:"max-w-xs text-xs",children:s})]})}function yn(e){const{user:t}=$t(),[r,a]=(0,fn.useState)(null),[s,n]=(0,fn.useState)(null),[i,o]=(0,fn.useState)(!0),[l,c]=(0,fn.useState)(null),d=(0,fn.useCallback)(async()=>
2{if(e&&t){o(!0),c(null);try{const[r,s]=await Promise.all([Lt.functions.invoke("telegram-setup",{body:{action:"status",projectId:e}}),Lt.from("telegram_user_links").select("id, telegram_username, linked_at").eq("project_id",e).eq("user_id",t.id).maybeSingle()]);if(r.error)throw r.error;const i=r.data;a({connected:!!i?.connected,botUsername:i?.botUsername||null,botId:i?.botId||null,linkedUserCount:i?.linkedUserCount||0}),n(s.data||null)}catch(r){const e=r instanceof Error?r.message:String(r);c(e)}finally{o(!1)}}},[e,t]);return(0,fn.useEffect)(()=>{d()},[d]),(0,fn.useEffect)(()=>{if(!e||!t)return;let r=null;return r=Lt.channel(Jt(`telegram-link-${e}-${t.id}`)).on("postgres_changes",{event:"INSERT",schema:"public",table:"telegram_user_links",filter:`user_id=eq.${t.id}`},t=>{const r=t.new;r.project_id===e&&n({id:r.id,telegram_username:r.telegram_username||null,linked_at:r.linked_at})}).on("postgres_changes",{event:"DELETE",schema:"public",table:"telegram_user_links",filter:`user_id=eq.${t.id}`},()=>n(null)).subscribe(),()=>{r&&Lt.removeChannel(r)}},[e,t]),{status:r,myLink:s,loading:i,error:l,connectBot:(0,fn.useCallback)(async t=>{if(!e)return{ok:!1,error:"No project"};try{const{data:r,error:a}=await Lt.functions.invoke("telegram-setup",{body:{action:"connect",projectId:e,botToken:t}});return a?{ok:!1,error:a.message}:r?.error?{ok:!1,error:r.error}:(await d(),{ok:!0})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},[e,d]),disconnectBot:(0,fn.useCallback)(async()=>{if(!e)return{ok:!1,error:"No project"};try{const{data:t,error:r}=await Lt.functions.invoke("telegram-setup",{body:{action:"disconnect",projectId:e}});return r?{ok:!1,error:r.message}:t?.error?{ok:!1,error:t.error}:(await d(),{ok:!0})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},[e,d]),refresh:d,generateLinkCode:(0,fn.useCallback)(async()=>{if(!(e&&t&&r?.connected&&r.botUsername))return null;const a=crypto.randomUUID().replace(/-/g,"").slice(0,16),s=new Date(Date.now()+9e5).toISOString();try{const{error:n}=await Lt.from("telegram_link_codes").insert({code:a,project_id:e,user_id:t.id,expires_at:s});if(n)throw new Error(n.message);return{code:a,deepLink:`https://t.me/${r.botUsername}?start=${a}`}}catch(n){throw c(n instanceof Error?n.message:String(n)),n}},[e,t,r]),unlinkMe:(0,fn.useCallback)(async()=>{if(e&&t&&s)try{const{error:e}=await Lt.from("telegram_user_links").delete().eq("id",s.id);if(e)throw new Error(e.message);n(null)}catch(r){throw c(r instanceof Error?r.message:String(r)),r}},[e,t,s])}}var wn=["SU","MO","TU","WE","TH","FR","SA"],Nn=864e5,kn=new Set(["FREQ","INTERVAL","COUNT","UNTIL","BYDAY","WKST"]),Sn=new Set(["BYHOUR","BYMINUTE","BYSECOND"]),In=e=>String(e).padStart(2,"0");function Cn(e){if(!e)return null;const t=/^(\d{4})-?(\d{2})-?(\d{2})$/.exec(e.trim());if(!t)return null;const r=Number(t[1]),a=Number(t[2]),s=Number(t[3]),n=new Date(r,a-1,s);return n.getFullYear()!==r||n.getMonth()!==a-1||n.getDate()!==s?null:n}function En(e){return e.toISOString().slice(0,10)}function Tn(e){return`${e.getUTCFullYear()}${In(e.getUTCMonth()+1)}${In(e.getUTCDate())}T${In(e.getUTCHours())}${In(e.getUTCMinutes())}${In(e.getUTCSeconds())}Z`}function An(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}var Dn=(e,t)=>(e%t+t)%t,On=e=>e-Dn(e,Nn),Rn=new Map;function Mn(e){let t=Rn.get(e);if(void 0===t){try{t=new Intl.DateTimeFormat("en-US",{timeZone:e,hourCycle:"h23",year:"numeric",month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",second:"numeric"})}catch{t=null}Rn.set(e,t)}return t}function Pn(e){return!!e&&!!e.trim()&&e.length<=64&&null!==Mn(e.trim())}function Ln(e){if(Pn(e))return e.trim();const t=An();return Pn(t)?t:"UTC"}function Un(e,t){return Pn(e)?e.trim():t}function $n(e,t){const r=Mn(t);if(!r||!Number.isFinite(e)||Math.abs(e)>864e13)return 0;const a={};for(const n of r.formatToParts(new Date(e)))"literal"!==n.type&&(a[n.type]=Number(n.value));const s=new Date(0);return s.setUTCFullYear(a.year,a.month-1,a.day),s.setUTCHours(a.hour%24,a.minute,a.second,0),s.getTime()-(e-Dn(e,1e3))}function Fn(e,t){const r="number"==typeof e?e:e.getTime();return r+$n(r,t)}function Wn(e,t){const r=$n(e-Nn,t),a=$n(e+Nn,t);
2return r===a?new Date(e-r):$n(e-a,t)===a?new Date(e-a):new Date(e-r)}function Kn(e,t){const r=new Date(e),a=r.getUTCMonth()+t,s=r.getUTCFullYear()+Math.floor(a/12),n=Dn(a,12),i=new Date(Date.UTC(s,n+1,0)).getUTCDate();return Date.UTC(s,n,Math.min(r.getUTCDate(),i))+(e-On(e))}function Hn(e,t){const r=new Date(e.start_time).getTime(),a=new Date(e.end_time).getTime(),s=Fn(r,t),n=0===(i=new Date(r)).getUTCHours()&&0===i.getUTCMinutes()&&0===i.getUTCSeconds()&&0===i.getUTCMilliseconds()&&0!==Dn(s,Nn);var i;const o=n?r:s,l=n?a:Fn(a,t),c=On(o);let d=c;return a>r&&(d=0===Dn(l,Nn)?n||e.time_zone?.trim()||e.import_source?l-Nn:l:On(l),d<c&&(d=c)),{firstWall:c,lastWall:d,utcDates:n,startDateWall:o,endDateWall:l}}function qn(e,t){const r=Ln(t),a=Hn(e,Un(e.time_zone,r));return{first:Wn(a.firstWall,r),last:Wn(a.lastWall,r),utcDates:a.utcDates}}function zn(e,t){const r=Ne(e),a=Ne(t).getTime()<r.getTime()?r:Ne(t);return{start_time:r.toISOString(),end_time:z(a,1).toISOString()}}function Vn(e,t){if(e.is_all_day){const r=Ln(t),a=Hn(e,Un(e.time_zone,r));return{start:Wn(a.firstWall,r),end:Wn(a.lastWall+Nn,r)}}const r=new Date(e.start_time),a=new Date(e.end_time);return{start:r,end:a.getTime()>r.getTime()?a:r}}function Bn(e){const t=new Map,r=e.trim().replace(/^RRULE:/i,"");for(const a of r.split(";")){const e=a.indexOf("=");e<=0||t.set(a.slice(0,e).trim().toUpperCase(),a.slice(e+1).trim().toUpperCase())}return t}function Gn(e,t,r){const a=Bn(e),s=t.toUpperCase();return null===r?a.delete(s):a.set(s,r),Array.from(a.entries()).map(([e,t])=>`${e}=${t}`).join(";")}function Yn(e,t){if(!e)return null;const r=e.trim().toUpperCase().replace(/[-:]/g,""),a=/^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/.exec(r);if(!a)return null;const s=Number(a[1]),n=Number(a[2]),i=Number(a[3]),o=Date.UTC(s,n-1,i),l=new Date(o);if(l.getUTCFullYear()!==s||l.getUTCMonth()!==n-1||l.getUTCDate()!==i)return null;const c=Ln(t);if(void 0===a[4]||"23"===a[4]&&"59"===a[5]&&"59"===a[6])return new Date(Wn(o+Nn,c).getTime()-1);const d=Number(a[4]),u=Number(a[5]),m=Number(a[6]);return d>23||u>59||m>59?null:a[7]?new Date(Date.UTC(s,n-1,i,d,u,m)):Wn(Date.UTC(s,n-1,i,d,u,m),c)}function Jn(e){const t=new Date(e.getTime()-6e4),r=Tn(t);return r.endsWith("T235959Z")?Tn(new Date(t.getTime()-1e3)):r}function Qn(e,t,r){if(!e||!e.trim())return null;const a=null!==t&&Number.isFinite(t)?new Date(t):null,s=Bn(e),n=s.get("FREQ");if("DAILY"!==n&&"WEEKLY"!==n&&"MONTHLY"!==n&&"YEARLY"!==n)return null;let i=!0;const o=Number(s.get("INTERVAL")??"1"),l=Number.isInteger(o)&&o>=1?Math.min(o,1e3):1,c=s.has("COUNT")?Number(s.get("COUNT")):NaN,d=Number.isInteger(c)&&c>=1?c:null,u=s.has("UNTIL")?Yn(s.get("UNTIL"),r):null,m=[],p=s.get("BYDAY");if(p){"WEEKLY"!==n&&(i=!1);for(const e of p.split(",")){const t=wn.indexOf(e.trim());t<0?i=!1:m.includes(t)||m.push(t)}}const h=wn.indexOf(s.get("WKST")??"MO"),f=h>=0?h:1;for(const[g,x]of s)kn.has(g)||Sn.has(g)||("BYMONTHDAY"!==g||!a||"MONTHLY"!==n&&"YEARLY"!==n||x!==String(a.getUTCDate()))&&("BYMONTH"===g&&a&&"YEARLY"===n&&x===String(a.getUTCMonth()+1)||(i=!1));return{freq:n,interval:l,count:d,until:u,byDay:m,weekStartsOn:f,supported:i}}function Zn(e,t){const r=Ln(t),a=Un(e.time_zone,r),s=new Date(e.start_time),n=new Date(e.end_time);if(e.is_all_day){const t=Hn(e,a);return{allDay:!0,zone:a,viewerZone:r,anchorWall:t.firstWall,durationMs:0,spanDays:Math.round((t.lastWall-t.firstWall)/Nn)+1,utcDates:t.utcDates,startWall:t.startDateWall,endWall:t.endDateWall,start:s,end:n}}const i=Fn(s,a);return{allDay:!1,zone:a,viewerZone:r,anchorWall:i,durationMs:Math.max(0,n.getTime()-s.getTime()),spanDays:0,utcDates:!1,startWall:i,endWall:Fn(n,a),start:s,end:n}}var Xn=e=>Number.isFinite(e.anchorWall)&&Number.isFinite(e.end.getTime()),ei=(e,t)=>Qn(e.recurrence_rule,t.anchorWall,t.zone);function ti(e,t,r,a){if(e.allDay){const s=Math.round((r-e.anchorWall)/Nn),n=(t,r)=>0===s?t:e.utcDates?new Date(t.getTime()+s*Nn):Wn(r+s*Nn,e.zone),i=n(e.start,e.startWall);return{index:t,start:i,end:n(e.end,e.endWall),visibleStart:Wn(r,e.viewerZone),visibleEnd:Wn(r+e.spanDays*Nn,e.viewerZone),excluded:a.size>0&&a.has(En(i))}}const s=r===e.anchorWall?e.start:Wn(r,e.zone),n=new Date(s.getTime()+e.durationMs);return{index:t,start:s,end:n,visibleStart:s,visibleEnd:n,excluded:a.size>0&&a.has(En(s))}}var ri=(e,t,r)=>e.visibleStart<r&&(e.visibleEnd>t||e.visibleEnd.getTime()===e.visibleStart.getTime()&&e.visibleStart>=t);function ai(e,t,r,a){const s=function(e){const t=e.exdates;return Array.isArray(t)?new Set(t.map(e=>String(e).slice(0,10))):new Set}(e),n=[],i=a.skipAhead?r.allDay?Fn(a.rangeStart,r.viewerZone)-(r.spanDays+2)*Nn:Fn(a.rangeStart,r.zone)-r.durationMs-Nn:0,o=On(r.anchorWall),l=r.anchorWall-o,c=e=>t.until&&e.start.getTime()>t.until.getTime()||e.visibleStart>=a.rangeEnd?"stop":(!a.includeExcluded&&e.excluded||!ri(e,a.rangeStart,a.rangeEnd)||n.push(e),"next");if("WEEKLY"===t.freq&&t.byDay.length>0){const e=t.weekStartsOn,d=t=>(t-e+7)%7,u=[...t.byDay].sort((e,t)=>
2d(e)-d(t)),m=o-d(new Date(o).getUTCDay())*Nn,p=u.filter(e=>m+d(e)*Nn>=o).length;let h=0;if(a.skipAhead){const e=Math.floor(Math.round((On(i)-m)/Nn)/7);h=Math.max(0,Math.floor(e/t.interval)-1)}let f=0;e:for(;f<2e4;h++){const e=m+h*t.interval*7*Nn;let a=0;for(const n of u){f++;const i=e+d(n)*Nn;if(0===h&&i<o)continue;const m=0===h?a:p+(h-1)*u.length+a;if(a++,null!==t.count&&m>=t.count)break e;if("stop"===c(ti(r,m,i+l,s)))break e}}return n}const d=e=>{const a=e*t.interval;switch(t.freq){case"DAILY":return r.anchorWall+a*Nn;case"WEEKLY":return r.anchorWall+7*a*Nn;case"MONTHLY":return Kn(r.anchorWall,a);default:return Kn(r.anchorWall,12*a)}};let u=0;if(a.skipAhead){const e=Math.round((On(i)-o)/Nn),r=new Date(i),a=new Date(o),s=r.getUTCFullYear()-a.getUTCFullYear(),n="DAILY"===t.freq?e:"WEEKLY"===t.freq?Math.floor(e/7):"MONTHLY"===t.freq?12*s+(r.getUTCMonth()-a.getUTCMonth()):s;u=Math.max(0,Math.floor(n/t.interval)-1)}for(let m=0;m<2e4&&!(null!==t.count&&u>=t.count)&&"stop"!==c(ti(r,u,d(u),s));m++,u++);return n}function si(e,t,r,a={}){const s=Zn(e,a.viewerTimeZone);if(!Xn(s))return[];const n=ei(e,s);if(!n||!n.supported){const e=ti(s,0,s.anchorWall,new Set);return ri(e,t,r)?[e]:[]}return ai(e,n,s,{rangeStart:t,rangeEnd:r,skipAhead:!0,includeExcluded:!!a.includeExcluded})}function ni(e,t,r,a={}){if(!e.recurrence_rule)return[e];const s=Zn(e,a.viewerTimeZone);if(!Xn(s))return[e];const n=ei(e,s);if(!n)return[e];if(!n.supported){const a=ti(s,0,s.anchorWall,new Set);return ri(a,t,r)?[e]:[]}return ai(e,n,s,{rangeStart:t,rangeEnd:r,skipAhead:!0,includeExcluded:!1}).map(t=>({...e,id:`${e.id}_r${t.index}`,start_time:t.start.toISOString(),end_time:t.end.toISOString()}))}function ii(e,t){return si(e,new Date(t.getTime()-2*Nn),new Date(t.getTime()+2*Nn),{includeExcluded:!0}).find(e=>Math.abs(e.start.getTime()-t.getTime())<=6e4)??null}function oi(e,t){const r=Date.parse(`${t}T00:00:00Z`);return Number.isFinite(r)?si(e,new Date(r-2*Nn),new Date(r+3*Nn),{includeExcluded:!0}).find(e=>En(e.start)===t)??null:null}function li(e,t){const r=Array.isArray(e.exdates)?e.exdates.map(e=>String(e).slice(0,10)):[],a=new Set;for(const s of r){const r=oi(e,s);a.add(r?En(t(r.start)):s)}return Array.from(a)}function ci(){return ua("recall-bot")}async function di(){const{data:{session:e}}=await Lt.auth.getSession();if(!e?.access_token)throw new Error("Not authenticated â please sign in to use meeting features");return{Authorization:`Bearer ${e.access_token}`,"Content-Type":"application/json"}}async function ui(){await Lt.auth.signOut(),window.location.href="/auth"}function mi(e,t){return 503===e.status||"BOT_API_UNREACHABLE"===t?.code}async function pi(e,t){const r=ci();if(!r)return{error:"Meeting bot integration is not configured for this environment"};const a=new URLSearchParams({action:e,...t}),s=await di(),n=await fetch(`${r}?${a}`,{headers:s});if(401===n.status)return await ui(),{error:"Session expired"};if(!n.ok){const t=await n.json().catch(()=>({error:`Bot service error (${n.status})`}));return mi(n,t)?Ge.warn(`[callBot] meeting service unreachable for action=${e} â backing off`):Ge.error(`[callBot] HTTP ${n.status} for action=${e}:`,t),{error:t.error||t.message||`Bot service error (${n.status})`,code:t.code}}return n.json()}async function hi(e,t){const r=ci();if(!r)return{error:"Meeting bot integration is not configured for this environment"};const a=await di(),s=await fetch(`${r}?action=${e}`,{method:"POST",headers:a,body:JSON.stringify(t)});if(401===s.status)return await ui(),{error:"Session expired"};if(!s.ok){const t=await s.json().catch(()=>({error:`Bot service error (${s.status})`}));return mi(s,t)?Ge.warn(`[postBot] meeting service unreachable for action=${e} â backing off`):Ge.error(`[postBot] HTTP ${s.status} for action=${e}:`,t),{error:t.error||t.message||`Bot service error (${s.status})`,code:t.code}}return s.json()}var fi={scheduling:{label:"Scheduled",color:"text-muted-foreground bg-muted",icon:fn.createElement(Ue,{className:"w-3 h-3"})},joining:{label:"Joining...",color:"text-amber-700 bg-amber-100 dark:text-amber-300 dark:bg-amber-900/30",icon:fn.createElement(ce,{className:"w-3 h-3 animate-spin"})},in_call:{label:"In Meeting",color:"text-red-700 bg-red-100 dark:text-red-300 dark:bg-red-900/30",icon:fn.createElement("div",{className:"w-2 h-2 rounded-full bg-red-500 animate-pulse"})},recording:{label:"Recording",color:"text-red-700 bg-red-100 dark:text-red-300 dark:bg-red-900/30",icon:fn.createElement("div",{className:"w-2 h-2 rounded-full bg-red-500 animate-pulse"})},processing:{label:"Processing",color:"text-blue-700 bg-blue-100 dar
2k:text-blue-300 dark:bg-blue-900/30",icon:fn.createElement(ce,{className:"w-3 h-3 animate-spin"})},done:{label:"Completed",color:"text-emerald-700 bg-emerald-100 dark:text-emerald-300 dark:bg-emerald-900/30",icon:fn.createElement(N,{className:"w-3 h-3"})},error:{label:"Failed",color:"text-destructive bg-destructive/10",icon:fn.createElement("span",{className:"w-2 h-2 rounded-full bg-destructive"})},cancelled:{label:"Cancelled",color:"text-muted-foreground bg-muted",icon:fn.createElement(l,{className:"w-3 h-3"})}};function gi(e){const t=fi[e];return t||{label:e?e.replace(/_/g," ").replace(/^\w/,e=>e.toUpperCase()):"Unknown",color:"text-muted-foreground bg-muted",icon:fn.createElement(Ue,{className:"w-3 h-3"})}}var xi=new Set(["FORBIDDEN","INVALID_REQUEST","SERIES_IN_OTHER_PROJECT"]),_i=e=>"number"==typeof e&&Number.isFinite(e)?e:0;function bi(e){const t=Array.isArray(e.scheduled)?e.scheduled:[],r=Array.isArray(e.failures)?e.failures:[];return{calendar_event_id:String(e.calendar_event_id),enabled:!0===e.enabled,recurring:!0===e.recurring,has_meeting_link:!1!==e.has_meeting_link,window_days:_i(e.window_days)||30,dispatched:_i(e.dispatched),cancelled:_i(e.cancelled),scheduled:t.filter(e=>e&&"string"==typeof e.occurrence_start),failures:r.filter(e=>e&&"string"==typeof e.code),partial:!0===e.partial}}async function ji(e){const t={calendar_event_id:e.calendarEventId,project_id:e.projectId,include_in_progress:!!e.includeInProgress};void 0!==e.enabled&&(t.enabled=e.enabled),e.botName?.trim()&&(t.bot_name=e.botName.trim()),e.fallbackTimeZone&&(t.fallback_time_zone=e.fallbackTimeZone);let r={ok:!1,error:"Unknown error"};for(let s=1;s<=2;s++){try{const e=await hi("sync_calendar_bots",t);if(e&&!e.error&&"string"==typeof e.calendar_event_id)return{ok:!0,result:bi(e)};if(r={ok:!1,error:String(e?.error??"Unknown error"),code:e?.code},r.code&&xi.has(r.code))break;if(/not configured/i.test(r.error))break}catch(a){r={ok:!1,error:a instanceof Error?a.message:"Network error"}}s<2&&await new Promise(e=>setTimeout(e,2e3))}return Ge.warn("Calendar notetaker sync failed",{calendarEventId:e.calendarEventId,error:r.ok?null:r.error}),r}async function vi(e,t){try{const r=await pi("calendar_bot_state",{calendar_event_id:e,project_id:t});return!r||r.error||"boolean"!=typeof r.enabled?null:{enabled:r.enabled,botName:"string"==typeof r.bot_name?r.bot_name:null}}catch(r){return Ge.warn("Could not load the calendar notetaker state",r),null}}async function yi(e){let t=Lt.from("user_calendar_events_manual").select("id, created_at").eq("start_time",e.startIso).neq("id",e.seriesId).gte("created_at",e.createdAfterIso).order("created_at",{ascending:!1}).limit(1);t=e.userId?t.eq("user_id",e.userId):t.is("user_id",null),t=e.projectId?t.eq("project_id",e.projectId):t.is("project_id",null),t=e.recurring?t.not("recurrence_rule","is",null):t.is("recurrence_rule",null);const{data:r,error:a}=await t;
2return a?(Ge.warn("Could not find the event created by a recurring edit",a),null):r&&r.length>0?r[0].id:null}var wi=new Set(["insufficient_wallet","project_allocation_exceeded"]);function Ni(e,t){const r=e.scheduled.filter(e=>"scheduling"===e.status||"joining"===e.status||null===e.status),a=e.failures;if(!e.enabled)return 0===e.cancelled?null:{tone:"info",message:1===e.cancelled?"The scheduled AI notetaker was cancelled. No credits were used.":`${e.cancelled} scheduled AI notetakers were cancelled. No credits were used.`};const s=a.find(e=>wi.has(e.code));if(s)return{tone:"warning",message:"project_allocation_exceeded"===s.code?"The notetaker can't join the meeting that's running now: this project's monthly credit allocation is used up.":"The notetaker can't join the meeting that's running now: you don't have enough credits."};if(a.length>0&&0===r.length)return{tone:"warning",message:`Event saved, but the notetaker couldn't be scheduled: ${a[0].error}`};if(0===e.dispatched&&0===e.cancelled&&0===a.length)return null;const n=a.length>0?` ${1===a.length?"One meeting":`${a.length} meetings`} couldn't be scheduled yet and will be retried.`:"",i=a.length>0?"warning":"success";if(e.recurring){if(0===r.length)return{tone:"info",message:`AI notetaker is on. No meetings in the next ${e.window_days} days yet â each one gets a notetaker as it comes up.`};const a=r.find(e=>Date.parse(e.join_at??e.occurrence_start)>=t.nowMs-36e5)??r[0],s=r.length;return{tone:i,message:`AI notetaker scheduled for ${s} upcoming ${1===s?"meeting":"meetings"} (next: ${t.formatDate(a.join_at??a.occurrence_start)}). Later meetings are added as they come within ${e.window_days} days. Credits are used only when it joins.${n}`}}const o=r[0];return o?{tone:i,message:o.join_at?`AI notetaker scheduled to join ${t.formatDate(o.join_at)}. Credits are used only when it joins.${n}`:`AI notetaker is joining the meeting now.${n}`}:null}var ki=({module:e,onBack:t,reason:r="disabled"})=>{const a=Vt(e)?.label??e;return(0,jn.jsxs)("div",{className:"flex flex-col items-center justify-center gap-4 py-24 px-6 text-center",children:[(0,jn.jsx)("div",{className:"w-14 h-14 rounded-full bg-muted flex items-center justify-center",children:(0,jn.jsx)(be,{className:"w-6 h-6 text-muted-foreground"})}),(0,jn.jsxs)("div",{className:"space-y-1.5 max-w-md",children:[(0,jn.jsx)("h2",{className:"text-lg font-semibold text-foreground",children:"restricted"===r?`You don't have access to ${a}`:`${a} is currently disabled`}),(0,jn.jsx)("p",{className:"text-sm text-muted-foreground",children:"restricted"===r?"A project admin hasn't given you access to this module. Ask them to grant access in Team Management.":"Your administrator has turned this module off. Your data is safe and will be available again as soon as it's re-enabled."})]}),t&&(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",onClick:t,children:[(0,jn.jsx)(I,{className:"w-4 h-4 mr-2"}),"Back"]})]})},Si=e=>e,Ii=null;function Ci(e){Ii=e}var Ei=(e,t={})=>{const{user:r}=$t(),a=!0===t.readOnly,[s,n]=(0,fn.useState)([]),[i,o]=(0,fn.useState)(!0),[l,c]=(0,fn.useState)(null),d=(0,fn.useCallback)(async()=>{if(e){try{const{data:t,error:s}=await Lt.from("whiteboards").select("*").eq("project_id",e).eq("is_archived",!1).order("updated_at",{ascending:!1});if(s)throw s;if(t&&t.length>0){const e=t.map(Si);n(e),c(t=>t??e[0])}else if(a)n([]);else{if(!r)return;{const{data:t,error:a}=await Lt.from("whiteboards").insert({project_id:e,name:"Main Board",created_by:r.id}).select().single();!a&&t&&(n([t]),c(t))}}}catch(t){Ge.error("Error fetching whiteboards:",t)}o(!1)}else o(!1)},[e,r,a]);(0,fn.useEffect)(()=>{d()},[d]),(0,fn.useEffect)(()=>{if(!e||!Ii)return;const t=Ii;Ii=null,Lt.from("whiteboards").select("*").eq("id",t).maybeSingle().then(({data:e})=>{if(e){const t=e;n(e=>e.some(e=>e.id===t.id)?e:[t,...e]),c(t)}},e=>Ge.error("Failed to load pending whiteboard",e,{whiteboardId:t}))},[e]),(0,fn.useEffect)(()=>{if(!e)return;const t=async e=>{const{whiteboardId:t}=e.detail||{};if(!t)return;const{data:r}=await Lt.from("whiteboards").select("*").eq("id",t).maybeSingle();if(r){const e=r;n(t=>t.some(t=>t.id===e.id)?t:[e,...t]),c(e)}};return window.addEventListener("select-whiteboard",t),()=>window.removeEventListener("select-whiteboard",t)},[e]),Qt(e,"whiteboards",{onInsert:e=>{n(t=>t.some(t=>t.id===e.id)?t:[e,...t])},onUpdate:e=>{n(t=>t.map(t=>
2t.id===e.id?{...t,...e}:t)),l?.id===e.id&&c(t=>t?{...t,...e}:null)},onDelete:e=>{n(t=>t.filter(t=>t.id!==e.id)),l?.id===e.id&&c(null)}},[]);const u=(0,fn.useCallback)(async(t="Untitled Board")=>{if(!e||!r||a)return null;try{const{data:a,error:s}=await Lt.from("whiteboards").insert({project_id:e,name:t,created_by:r.id}).select().single();if(s)throw s;const i=a;return n(e=>[i,...e]),c(i),Ae.success(dt("wb.board_created_new")),i}catch(s){return Ge.error("Error creating whiteboard:",s),Yr(s,{projectId:e})||Ae.error(dt("wb.board_create_failed")),null}},[e,r,a]);return{whiteboards:s,loading:i,currentWhiteboard:l,setCurrentWhiteboard:c,createWhiteboard:u,updateWhiteboard:async(t,r)=>{if(a)return null;try{const{data:e,error:a}=await Lt.from("whiteboards").update(r).eq("id",t).select().single();if(a)throw a;const s=e;return n(e=>e.map(e=>e.id===t?s:e)),l?.id===t&&c(s),s}catch(s){return Ge.error("Error updating whiteboard:",s),Yr(s,{projectId:e})||Ae.error(dt("wb.board_update_failed")),null}},deleteWhiteboard:async t=>{if(!a)try{const{data:e,error:r}=await Lt.from("whiteboards").delete().eq("id",t).select("id");if(r)throw r;if(!e?.length)throw new Error("Board delete matched no rows (no edit access or already deleted)");if(n(e=>e.filter(e=>e.id!==t)),l?.id===t){const e=s.filter(e=>e.id!==t);c(e[0]||null)}Ae.success(dt("wb.board_deleted"))}catch(r){Ge.error("Error deleting whiteboard:",r),Yr(r,{projectId:e})||Ae.error(dt("wb.board_delete_failed"))}},duplicateWhiteboard:async t=>{if(!e||!r||a)return null;try{const{data:e,error:r}=await Lt.rpc("duplicate_whiteboard",{p_board_id:t});if(r)throw r;const a=e,s=Array.isArray(a)?a[0]:a;if(!s?.id)throw new Error("duplicate_whiteboard returned no board");const i=s;return n(e=>e.some(e=>e.id===i.id)?e:[i,...e]),Ae.success(dt("wb.board_duplicated")),i}catch(s){return Ge.error("Error duplicating whiteboard:",s,{whiteboardId:t}),Yr(s,{projectId:e})||Ae.error(dt("wb.board_duplicate_failed")),null}},refreshWhiteboards:d}};async function Ti(){const{data:{session:e}}=await Lt.auth.getSession();return e?.access_token?{Authorization:`Bearer ${e.access_token}`,"Content-Type":"application/json"}:null}var Ai={events:[],truncated:!1,coveredUntil:null};var Di=null,Oi=null;async function Ri(){if(Di&&Date.now()-Di.at<6e4)return Di.value;const e=(await async function(){const{data:{user:e}}=await Lt.auth.getUser();if(!e)return[];const{data:t,error:r}=await Lt.from("user_calendar_connections").select("provider, scopes").eq("user_id",e.id).eq("scopes","readwrite");return r?(Ge.warn("[calendar mirror] failed to load writeable providers:",r),[]):(t||[]).map(e=>e.provider).filter(e=>"google"===e||"outlook"===e)}()).length>0;return Di={at:Date.now(),value:e},e}function Mi(e=1500){Oi&&clearTimeout(Oi),Oi=setTimeout(()=>{Oi=null,(async()=>{try{if(!(await Ri()))return;const e=await Ti(),t=ua("calendar-events");if(!e||!t)return;const r=await fetch(t,{method:"POST",headers:e,keepalive:!0,body:JSON.stringify({action:"sync_pending"})});r.ok||Ge.warn(`[calendar mirror] sync_pending returned ${r.status}`)}catch(e){Ge.warn("[calendar mirror] sync_pending failed:",e)}})()},Math.max(0,e))}var Pi={blue:{bg:"bg-blue-500/15",text:"text-blue-700 dark:text-blue-400",dot:"bg-blue-500"},red:{bg:"bg-red-500/15",text:"text-red-700 dark:text-red-400",dot:"bg-red-500"},green:{bg:"bg-green-500/15",text:"text-green-700 dark:text-green-400",dot:"bg-green-500"},purple:{bg:"bg-purple-500/15",text:"text-purple-700 dark:text-purple-400",dot:"bg-purple-500"},orange:{bg:"bg-orange-500/15",text:"text-orange-700 dark:text-orange-400",dot:"bg-orange-500"},teal:{bg:"bg-teal-500/15",text:"text-teal-700 dark:text-teal-400",dot:"bg-teal-500"}},Li=/^(.+)_r(\d+)$/,Ui="ext:";function $i(e){return e.startsWith(Ui)}function Fi(e){if($i(e))return e;const t=Li.exec(e);return t?t[1]:e}function Wi(e){return!$i(e)&&Li.test(e)}function Ki(e){return!!e.import_source||!!e.event_uid&&!!e.source_filename&&"builtin"!==e.source_filename}var Hi=1e3;async function qi(e){const t=[];for(let r=0;r<10;r++){const a=r*Hi,{data:s,error:n}=await e(a,a+Hi-1);if(n)return{data:t,error:n};if(t.push(...s||[]),!s||s.length<Hi)break}return{data:t,error:null}}var zi=(e,t,r)=>{const a=Vn(e);return a.start<r&&(a.end>t||a.end.getTime()===a.start.getTime()&&a.start>=t)};function Vi(e){let t=e.start,r=e.end,a=null;if(e.isAllDay){const s=Cn(e.start.slice(0,10)),n=Cn(e.end.slice(0,10));s&&(t=s.toISOString(),r=(n&&n>s?n:z(s,1)).toISOString(),a=An()||"UTC")}
2const s=[e.location,e.meetingLink].filter(Boolean).join(" ").trim();return{id:`${Ui}${e.provider}:${e.id}`,title:e.title||"Untitled",description:e.description||null,start_time:t,end_time:r,location:s||null,attendees:null,is_all_day:e.isAllDay,color:"google"===e.provider?"blue":"teal",recurrence_rule:null,reminder_minutes:null,source_filename:null,time_zone:a,read_only:!0,external_provider:e.provider,source_label:"google"===e.provider?"Google Calendar":"Microsoft Outlook",html_link:e.htmlLink}}var Bi=e=>e?.provider_event_ids&&"object"==typeof e.provider_event_ids?e.provider_event_ids:{};function Gi(e,t){const r=g(t,e),a=60*t.getHours()+t.getMinutes()-(60*e.getHours()+e.getMinutes());return e=>m(z(e,r),a)}async function Yi(e){const{data:t,error:r}=await Lt.from("user_calendar_events_manual").select("*").eq("id",e).maybeSingle();return{row:t??null,error:r}}function Ji(e,t){return{...e,mirror_to_providers:!!t}}function Qi(e){const{user:t}=$t(),{t:r}=at(),a=ir(),[s,n]=(0,fn.useState)([]),[i,o]=(0,fn.useState)(!1),l=(0,fn.useRef)(0),c=(0,fn.useRef)(null),d=e?`project_id.eq.${e},project_id.is.null`:"project_id.is.null";return{events:s,loading:i,fetchEvents:(0,fn.useCallback)(async(a,s,i={})=>{if(!t)return;const u=++l.current;o(!0);try{const o=z(a,-2).toISOString(),m=z(s,2).toISOString(),p=()=>Lt.from("user_calendar_events_manual"),h=qi((e,r)=>p().select("*").eq("user_id",t.id).or(d).is("recurrence_rule",null).lt("start_time",m).gte("end_time",o).order("start_time",{ascending:!0}).range(e,r)),f=qi((e,r)=>p().select("*").eq("user_id",t.id).or(d).not("recurrence_rule","is",null).lt("start_time",m).order("start_time",{ascending:!0}).range(e,r)),g=e?qi((t,r)=>p().select("*").eq("project_id",e).is("user_id",null).is("recurrence_rule",null).lt("start_time",m).gte("end_time",o).order("start_time",{ascending:!0}).range(t,r)):Promise.resolve({data:[],error:null}),x=e?qi((t,r)=>p().select("*").eq("project_id",e).is("user_id",null).not("recurrence_rule","is",null).lt("start_time",m).order("start_time",{ascending:!0}).range(t,r)):Promise.resolve({data:[],error:null}),_=i.includeProviders?async function(e,t){const r=await Ti();if(!r)return Ai;const a=ua("calendar-events");if(!a)return Ai;try{const s=await fetch(a,{method:"POST",headers:r,body:JSON.stringify({action:"list_events",external_only:!0,time_min:e.toISOString(),time_max:t.toISOString()})});if(!s.ok)return Ge.warn(`[calendar] provider events returned ${s.status}`),Ai;const n=await s.json();return{events:(Array.isArray(n?.events)?n.events:[]).map(e=>e).filter(e=>("google"===e.provider||"outlook"===e.provider)&&"string"==typeof e.id&&"string"==typeof e.start).map(e=>({provider:e.provider,id:String(e.id),seriesId:"string"==typeof e.seriesId&&e.seriesId?e.seriesId:null,title:"string"==typeof e.title?e.title:"Untitled",description:"string"==typeof e.description?e.description:"",location:"string"==typeof e.location?e.location:"",meetingLink:"string"==typeof e.meetingLink?e.meetingLink:"",start:String(e.start),end:"string"==typeof e.end&&e.end?e.end:String(e.start),isAllDay:!!e.isAllDay,status:"string"==typeof e.status?e.status:"",htmlLink:"string"==typeof e.htmlLink?e.htmlLink:null})),truncated:!0===n?.truncated,coveredUntil:"string"==typeof n?.covered_until?n.covered_until:null}}catch(s){return Ge.warn("[calendar] provider events fetch failed:",s),Ai}}(a,s):Promise.resolve({events:[],truncated:!1,coveredUntil:null}),[b,j,v,y,w]=await Promise.all([h,f,g,x,_]);if(u!==l.current)return;if(b.error||j.error)return Ge.error("Failed to fetch calendar events",b.error||j.error),void Ae.error(r("cal.events_load_failed"));(v.error||y.error)&&Ge.warn("Failed to fetch project calendar events:",v.error||y.error);const N=w.events;if(w.truncated){const e=`${a.toISOString()}|${s.toISOString()}`;c.current!==e&&(c.current=e,Ge.warn("[calendar] provider events truncated",{coveredUntil:w.coveredUntil}),Ae.info(r("cal.provider_events_truncated"),{id:"calendar-provider-events-truncated"}))}const k=new Map;for(const e of[...b.data,...j.data,...v.data,...y.data])k.set(e.id,e);const S=[],I=new Set;for(const e of k.values()){for(const[r,a]of Object.entries(Bi(e)))a&&I.add(`${r}:${a}`);const t=Ki(e)?{...e,read_only:!0,source_label:e.source_filename||"Imported calendar"}:e;for(const e of ni(t,a,s))(Wi(e.id)||zi(e,a,s))&&S.push(e)}
2for(const e of N){if("cancelled"===e.status)continue;if(I.has(`${e.provider}:${e.id}`))continue;if(e.seriesId&&I.has(`${e.provider}:${e.seriesId}`))continue;const t=Vi(e);zi(t,a,s)&&S.push(t)}S.sort((e,t)=>new Date(e.start_time).getTime()-new Date(t.start_time).getTime()),n(S)}catch(m){u===l.current&&(Ge.error("Failed to fetch builtin events:",m),Ae.error(r("cal.events_load_failed")))}finally{u===l.current&&o(!1)}},[t,d,e,r]),createEvent:(0,fn.useCallback)(async s=>{if(!t)return null;const{data:n,error:i}=await Lt.from("user_calendar_events_manual").insert({user_id:t.id,title:s.title,start_time:s.start_time,end_time:s.end_time,description:s.description||null,location:s.location||null,attendees:s.attendees||null,is_all_day:s.is_all_day||!1,color:s.color||"blue",recurrence_rule:s.recurrence_rule||null,reminder_minutes:s.reminder_minutes??null,source_filename:"builtin",project_id:a?null:s.project_id||e||null,time_zone:s.time_zone||An()||null,visibility:s.visibility||"default",task_id:s.task_id||null,mirror_to_providers:!0}).select().single();return i?(Ae.error(r("cal.event_create_failed")),Ge.error("Failed to create calendar event",i),null):(Ae.success(r("cal.event_created",{title:s.title})),Mi(),n)},[t,e,a,r]),updateEvent:(0,fn.useCallback)(async(e,s,n="all")=>{if(!t)return!1;if($i(e))return Ae.error(r("cal.event_read_only")),!1;const i=Fi(e),o=Wi(e),l=()=>Lt.from("user_calendar_events_manual"),c=(e,t)=>(e&&Ge.error("Failed to update calendar event",e,{eventId:i,scope:n}),Ae.error(t??r("cal.event_update_failed")),!1),{row:d,error:u}=await Yi(i);if(u)return c(u);if(!d)return c(null,r("cal.event_not_editable"));if(Ki(d))return c(null,r("cal.event_read_only"));if(a&&d.project_id)return c(null,r("cal.viewer_read_only"));const m=s.original_start?new Date(s.original_start):null,p=d.recurrence_rule||"",h=Math.max(0,new Date(d.end_time).getTime()-new Date(d.start_time).getTime()),f=e=>void 0!==s.attendees?s.attendees.length?s.attendees:null:e,x=void 0!==s.start_time?s.time_zone||An()||d.time_zone||null:d.time_zone??null;if(o&&"this"===n){const e=m??new Date(d.start_time),t=ii(d,e),a=t?.start??e,n=t?.end??new Date(a.getTime()+h),o=En(a),u=Array.isArray(d.exdates)?d.exdates.map(String):[],p=u.includes(o)?u:[...u,o],{data:g,error:_}=await l().insert(Ji({user_id:d.user_id??null,project_id:d.project_id??null,title:s.title??d.title,start_time:s.start_time??a.toISOString(),end_time:s.end_time??n.toISOString(),description:void 0!==s.description?s.description||null:d.description,location:void 0!==s.location?s.location||null:d.location,attendees:f(d.attendees),is_all_day:s.is_all_day??d.is_all_day??!1,color:s.color??d.color??"blue",reminder_minutes:"reminder_minutes"in s?s.reminder_minutes??null:d.reminder_minutes,source_filename:"builtin",time_zone:x,visibility:s.visibility??d.visibility??"default",kind:d.kind??"event",task_id:d.task_id??null,recurrence_rule:null},d.mirror_to_providers)).select("*").maybeSingle();if(_||!g)return c(_,_?void 0:r("cal.event_not_editable"));const{data:b,error:j}=await l().update({exdates:p}).eq("id",i).select("*");return j||!b||0===b.length?(await l().delete().eq("id",g.id),c(j,j?void 0:r("cal.event_not_editable"))):(Ae.success(r("cal.occurrence_updated")),Mi(),!0)}if(o&&"this_and_following"===n&&m){const e=ii(d,m);if(e&&e.index>0){const t=new Date(s.start_time??e.start.toISOString()),a=new Date(s.end_time??new Date(t.getTime()+h).toISOString()),n=Gi(e.start,t),o=void 0!==s.recurrence_rule&&(s.recurrence_rule||"")!==p;let u=void 0!==s.recurrence_rule?s.recurrence_rule||"":p;const m=function(e,t,r){const a=Ln(r);return Qn(e,t?Fn(t,a):null,a)}(p);if(!o&&u&&m?.count){const t=m.count-function(e,t){const r=Zn(e);if(!Xn(r))return 0;const a=ei(e,r);return a&&a.supported?ai(e,a,r,{rangeStart:new Date(-864e13),rangeEnd:t,skipAhead:!1,includeExcluded:!0}).filter(e=>e.start<t).length:r.start<t?1:0}(d,e.start);u=Gn(u,"COUNT",String(Math.max(1,t)))}const g=[],_=[];for(const r of Array.isArray(d.exdates)?d.exdates.map(String):[]){const t=oi(d,r);t&&t.start<e.start?g.push(r):_.push(r)}const b=o?[]:li({...d,exdates:_},n),j=Gn(Gn(p,"COUNT",null),"UNTIL",Jn(e.start)),{data:v,error:y}=await l().insert(Ji({user_id:d.user_id??null,project_id:d.project_id??null,title:s.title??d.title,start_time:t.toISOString(),end_time:a.toISOString(),description:void 0!==s.description?s.description||null:d.description,location:void 0!==s.location?s.location||null:d.location,attendees:f(d.attendees),is_all_day:s.is_all_day??d.is_all_day??!1,color:s.color??d.color??"blue",reminder_minutes:"reminder_minutes"in s?s.reminder_minutes??null:d.reminder_minutes,source_filename:"builtin",time_zone:x,visibility:s.visibility??d.visibility??"default",kind:d.kind??"event",task_id:d.task_id??null,recurrence_rule:u||null,exdates:b},d.mirror_to_providers)).select("*").maybeSingle();if(y||!v)return c(y,y?void 0:r("cal.event_not_editable"));const{data:w,error:N}=await l().update({recurrence_rule:j,exdates:g}).eq("id",i).select("*");return N||!w||0===w.length?(await l().delete().eq("id",v.id),c(N,N?void 0:r("cal.event_not_editable"))):(Ae.success(r("cal.series_updated_forward")),Mi(),!0)}}const _={};if(void 0!==s.title&&(_.title=s.title),o&&m&&s.start_time){const e=new Date(s.start_time),t=new Date(s.end_time??new Date(e.getTime()+h).toISOString()),r=Gi(ii(d,m)?.start??m,e),a=s.is_all_day??!!d.is_all_day,n=r(d.is_all_day?qn(d).first:new Date(d.start_time));let i,o;a?(i=Ne(n),o=z(i,Math.max(1,g(t,e)))):(i=n,o=new Date(n.getTime()+Math.max(0,t.getTime()-e.getTime()))),i.getTime()!==new Date(d.start_time).getTime()&&(_.start_time=i.toISOString()),o.getTime()!==new Date(d.end_time).getTime()&&(_.end_time=o.toISOString());const l=void 0===s.recurrence_rule||(s.recurrence_rule||"")===p;_.start_time&&l&&Array.isArray(d.exdates)&&d.exdates.length>0&&(_.exdates=li(d,r))}else void 0!==s.start_time&&(_.start_time=s.start_time),void 0!==s.end_time&&(_.end_time=s.end_time);if(void 0!==s.description&&(_.description=s.description||null),void 0!==s.location&&(_.location=s.location||null),void 0!==s.attendees&&(_.attendees=s.attendees.length?s.attendees:null),void 0!==s.is_all_day&&(_.is_all_day=s.is_all_day),void 0!==s.color&&(_.color=s.color),void 0!==s.recurrence_rule&&(_.recurrence_rule=s.recurrence_rule||null),"reminder_minutes"in s&&(_.reminder_minutes=s.reminder_minutes??null),void 0===_.start_time&&void 0===_.end_time||(_.time_zone=s.time_zone||An()||d.time_zone||null),void 0!==s.visibility&&(_.visibility=s.visibility),0===Object.keys(_).length)return Ae.success(r("cal.event_updated")),!0;const{data:b,error:j}=await l().update(_).eq("id",i).select("*");if(j)return c(j);if(!b||0===b.length)return c(null,r("cal.event_not_editable"));if(void 0!==s.title){const{error:e}=await Lt.from("meeting_sessions").update({title:s.title}).eq("calendar_event_id",i).eq("user_id",t.id);e&&Ge.warn("meeting_sessions title sync failed:",e);const{error:r}=await Lt.from("meeting_recordings").update({title:s.title}).eq("calendar_event_id",i).eq("user_id",t.id);r&&Ge.warn("meeting_recordings title sync failed:",r)}return Ae.success(r("cal.event_updated")),Mi(),!0},[t,a,r]),deleteEvent:(0,fn.useCallback)(async(e,s="all",n,i={})=>
2{if(!t)return!1;const o=!i.silent,l=(t,a)=>(t&&Ge.error("Failed to delete calendar event",t,{eventId:e,scope:s}),o&&Ae.error(a??r("cal.event_delete_failed")),!1);if($i(e))return l(null,r("cal.event_read_only"));const c=Fi(e),d=Wi(e),u=()=>Lt.from("user_calendar_events_manual"),{row:m,error:p}=await Yi(c);if(p)return l(p);if(!m)return l(null,r("cal.event_not_editable"));if(Ki(m))return l(null,r("cal.event_read_only"));if(a&&m.project_id)return l(null,r("cal.viewer_read_only"));if(d&&"this"===s){const e=n?new Date(n):new Date(m.start_time),t=ii(m,e),a=En(t?.start??e),s=Array.isArray(m.exdates)?m.exdates.map(String):[],i=s.includes(a)?s:[...s,a],{data:d,error:p}=await u().update({exdates:i}).eq("id",c).select("*");return p?l(p):d&&0!==d.length?(o&&Ae.success(r("cal.occurrence_removed")),Mi(),!0):l(null,r("cal.event_not_editable"))}if(d&&"this_and_following"===s&&n){const e=ii(m,new Date(n));if(e&&e.index>0){const t=Gn(Gn(m.recurrence_rule||"","COUNT",null),"UNTIL",Jn(e.start)),{data:a,error:s}=await u().update({recurrence_rule:t}).eq("id",c).select("*");return s?l(s):a&&0!==a.length?(o&&Ae.success(r("cal.series_ended_forward")),Mi(),!0):l(null,r("cal.event_not_editable"))}}const{data:h,error:f}=await u().delete().eq("id",c).select("id");return f?l(f):h&&0!==h.length?(Mi(),o&&Ae.success(r("cal.event_deleted")),!0):l(null,r("cal.event_not_editable"))},[t,a,r]),searchEvents:(0,fn.useCallback)(async e=>{if(!t||!e.trim())return[];const{data:r,error:a}=await Lt.from("user_calendar_events_manual").select("*").eq("user_id",t.id).or(d).ilike("title",`%${e.trim()}%`).order("start_time",{ascending:!1}).limit(20);return a?(Ge.warn("Calendar search failed",a),[]):(r||[]).map(e=>Ki(e)?{...e,read_only:!0,source_label:e.source_filename||"Imported calendar"}:e)},[t,d])}}async function Zi(){try{const{data:e}=await Lt.auth.getSession();let t=e.session;const r=Math.floor(Date.now()/1e3);return(!t?.access_token||!t?.expires_at||t.expires_at<=r+60)&&(t=(await Lt.auth.refreshSession()).data.session??t),t?.access_token??null}catch(e){return Ge.error("[auth] getFreshAccessToken failed",e),null}}var Xi={terse:"pa.hint_concise",detailed:"pa.hint_detailed"},eo={empathetic:"pa.hint_warm",tactical:"pa.hint_tactical"};function to({projectId:e}){const{t:t}=at(),{user:r}=$t(),[a,s]=(0,fn.useState)([]),[n,i]=(0,fn.useState)(null),[o,l]=(0,fn.useState)(!0),[c,d]=(0,fn.useState)(!1);(0,fn.useEffect)(()=>{if(!e||!r)return;(async()=>{l(!0);try{const[t,a]=await Promise.all([Lt.from("pa_facts").select("id, content, fact_type, source, created_at").eq("project_id",e).eq("scope","user").eq("user_id",r.id).is("superseded_by",null).order("created_at",{ascending:!1}).limit(20),Lt.from("pa_user_preference_signals").select("preferred_verbosity, preferred_tone").eq("user_id",r.id).eq("project_id",e).maybeSingle()]);t.error?Ge.error("Failed to load learned facts:",t.error):s(t.data||[]);const n=a;!n.error&&n.data&&i(n.data)}catch(t){Ge.error("Failed to load learned facts:",t)}finally{l(!1)}})()},[e,r]);const u=[];if(n){const e=Xi[n.preferred_verbosity],t=eo[n.preferred_tone];e&&u.push(e),t&&u.push(t)}const m=u.map(e=>t(e)).join(` ${t("common.and")} `),p=u.length>0?(0,jn.jsxs)("div",{className:"text-xs rounded-lg border border-border/50 bg-muted/20 p-2.5",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 mb-1 font-medium text-foreground",children:[(0,jn.jsx)(se,{className:"h-3.5 w-3.5"})," ",t("pa.learned_from_feedback")]}),(0,jn.jsx)("p",{className:"text-muted-foreground",children:t("pa.learned_summary",{hints:m})})]}):null,h=e=>{switch(e){case"preference":return"bg-blue-500/10 text-blue-700";case"role":return"bg-purple-500/10 text-purple-700";case"process":return"bg-amber-500/10 text-amber-700";case"goal":return"bg-green-500/10 text-green-700";case"constraint":return"bg-red-500/10 text-red-700";case"relationship":return"bg-pink-500/10 text-pink-700";case"tool":return"bg-cyan-500/10 text-cyan-700";default:return"bg-gray-500/10 text-gray-700"}};return o?(0,jn.jsx)("div",{className:"flex items-center justify-center py-6 text-muted-foreground",children:(0,jn.jsx)("div",{className:"animate-spin rounded-full h-5 w-5 border-2 border-primary border-t-transparent"})}):0===a.length?(0,jn.jsxs)("div",{className:"space-y-3",children:[p,(0,jn.jsxs)("div",{className:"py-4 px-3 rounded-lg bg-muted/30 text-center",children:[(0,jn.jsx)(Re,{className:"h-8 w-8 mx-auto mb-2 opacity-30"}),(0,jn.jsx)("p",{className:"text-sm text-muted-foreground",children:t("pa.no_learned_facts")})]})]}):(0,jn.jsxs)("div",{className:"space-y-3",children:[p,(0,jn.jsxs)("div",{className:"text-xs text-muted-foreground mb-3 flex items-start gap-2",children:[(0,jn.jsx)(Re,{className:"h-3.5 w-3.5 mt-0.5 flex-shrink-0"}),(0,jn.jsx)("span",{children:20===a.length?t("pa.learned_fact_count_at_least"):t(1===a.length?"pa.learned_fact_count":"pa.learned_fact_count_plural",{c
2ount:a.length})})]}),(0,jn.jsx)("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:a.map(e=>(0,jn.jsxs)("div",{className:"flex items-start gap-2 p-2 rounded border border-border/50 bg-muted/20",children:[(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 mb-0.5",children:[(0,jn.jsx)("span",{className:`text-[10px] font-medium px-1.5 py-0.5 rounded ${h(e.fact_type)}`,children:e.fact_type}),e.source&&(0,jn.jsx)("span",{className:"text-[10px] text-muted-foreground",children:e.source})]}),(0,jn.jsx)("p",{className:"text-xs text-foreground line-clamp-2",children:e.content})]}),(0,jn.jsx)("button",{onClick:()=>(async e=>{if(r)try{const{error:a}=await Lt.from("pa_facts").delete().eq("id",e).eq("user_id",r.id);if(a)return Ge.error("forgetFact delete failed:",a),void Ae.error(t("pa.forget_failed"));s(t=>t.filter(t=>t.id!==e)),Ae.success(t("pa.forgotten"))}catch{Ae.error(t("pa.forget_failed"))}})(e.id),className:"p-1 opacity-50 hover:opacity-100 hover:text-destructive transition-all flex-shrink-0",title:t("pa.forget_fact"),children:(0,jn.jsx)(f,{className:"h-3 w-3"})})]},e.id))}),a.length>0&&(0,jn.jsx)("div",{className:"pt-2 border-t border-border",children:c?(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsxs)("div",{className:"flex items-start gap-2 text-xs text-destructive bg-destructive/10 p-2 rounded",children:[(0,jn.jsx)(A,{className:"h-3.5 w-3.5 mt-0.5 flex-shrink-0"}),(0,jn.jsx)("span",{children:t("pa.forget_all_warning")})]}),(0,jn.jsxs)("div",{className:"flex gap-2",children:[(0,jn.jsx)(Ye,{size:"sm",variant:"destructive",className:"h-7 text-xs flex-1",onClick:async()=>{if(e&&r)try{const{error:a}=await Lt.from("pa_facts").delete().eq("project_id",e).eq("scope","user").eq("user_id",r.id);if(a)return Ge.error("forgetAll delete failed:",a),void Ae.error(t("pa.forget_retry"));s([]),d(!1),Ae.success(t("pa.all_facts_forgotten"))}catch{Ae.error(t("pa.forget_facts_failed"))}},children:t("pa.yes_forget_all")}),(0,jn.jsx)(Ye,{size:"sm",variant:"outline",className:"h-7 text-xs flex-1",onClick:()=>d(!1),children:t("action.cancel")})]})]}):(0,jn.jsxs)(Ye,{size:"sm",variant:"ghost",className:"h-7 text-xs text-muted-foreground w-full",onClick:()=>d(!0),children:[(0,jn.jsx)(f,{className:"h-3 w-3 mr-1.5"}),t("pa.forget_all_facts")]})})]})}var ro=["ð¤","ð§ ","ð¡","ð¯","â¡","ð","ð¦¾","ð®"],ao=[{key:"reminders_enabled",labelKey:"pa.pref_reminders",descriptionKey:"pa.pref_reminders_desc"},{key:"follow_ups_enabled",labelKey:"pa.pref_followups",descriptionKey:"pa.pref_followups_desc"},{key:"daily_greeting_enabled",labelKey:"pa.pref_daily_greeting",descriptionKey:"pa.pref_daily_greeting_desc"},{key:"proactive_nudges_enabled",labelKey:"pa.pref_proactive",descriptionKey:"pa.pref_proactive_desc"},{key:"break_reminders_enabled",labelKey:"pa.pref_breaks",descriptionKey:"pa.pref_breaks_desc"},{key:"confirm_outward_actions",labelKey:"pa.pref_confirm_outward",descriptionKey:"pa.pref_confirm_outward_desc"}];function so({open:e,onOpenChange:t,preferences:r,onUpdate:a,assistantName:n="Assad",projectId:i,defaultAvatar:o="ð¤",imageOptions:l=[]}){const{t:c}=at(),d=r.selected_avatar||"",[u,m]=(0,fn.useState)("settings");return(0,jn.jsx)(xt,{open:e,onOpenChange:t,children:(0,jn.jsxs)(ht,{className:"sm:max-w-md",children:[(0,jn.jsxs)(mt,{children:[(0,jn.jsxs)(ft,{className:"flex items-center gap-2",children:[(0,jn.jsx)(s,{className:"h-4 w-4 text-muted-foreground"}),c("pa.preferences_title",{name:n})]}),(0,jn.jsx)(gt,{children:c("pa.preferences_desc",{name:n})})]}),(0,jn.jsxs)(ya,{value:u,onValueChange:m,className:"w-full",children:[(0,jn.jsxs)(va,{className:"grid w-full grid-cols-2 mb-4",children:[(0,jn.jsx)(ba,{value:"settings",className:"text-xs",children:c("pa.tab_settings")}),(0,jn.jsx)(ba,{value:"learning",className:"text-xs",children:c("pa.tab_learning")})]}),(0,jn.jsxs)(ja,{value:"settings",className:"space-y-4 py-2",children:[ao.map(({key:e,labelKey:t,descriptionKey:s})=>(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"text-sm font-medium text-foreground",children:c(t)}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:c(s)})]}),(0,jn.jsx)(sa,{"aria-label":c(t),checked:r[e],onCheckedChange:t=>a(e,t)})]},e)),(0,jn.jsxs)("div",{className:"pt-2 border-t border-border space-y-4",children:[(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"text-sm font-medium text-foreground",children:c("pa.personality")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:c("pa.personality_desc",{name:n})})]}),(0,jn.jsxs)(aa,{value:r.preferred_personality,onValueChange:e=>a("preferred_personality",e),children:[(0,jn.jsx)(ea,{className:"w-32 h-8 text-xs",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"friendly",children:c("pa.personality_friendly")}),(0,jn.jsx)(ra,{value:"professional",children:c("pa.personality_professional")}),(0,jn.jsx)(ra,{value:"casual",children:c("pa.personality_casual")}),(0,jn.jsx)(ra,{value:"coach",children:c("pa.personality_coach")}),(0,jn.jsx)(ra,{value:"lovely",children:c("pa.personality_lovely")})]})]})]}),(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"text-sm font-medium text-foreground",children:c("pa.voice")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:c("pa.voice_desc",{name:n})})]}),(0,jn.jsxs)(aa,{value:r.preferred_voice_gender,onValueChange:e=>a("preferred_voice_gender",e),children:[(0,jn.jsx)(ea,{className:"w-32 h-8 text-xs",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"male",children:c("pa.voice_male")}),(0,jn.jsx)(ra,{value:"female",children:c("pa.voice_female")})]})]})]}),(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"text-sm font-medium text-foreground",children:c("pa.reply_length")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:c("pa.reply_length_desc",{name:n})})]}),(0,jn.jsxs)(aa,{value:r.override_verbosity||"auto",onValueChange:e=>a("override_verbosity",e),children:[(0,jn.jsx)(ea,{className:"w-32 h-8 text-xs",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"auto",children:c("pa.auto")}),(0,jn.jsx)(ra,{value:"terse",children:c("pa.concise")}),(0,jn.jsx)(ra,{value:"standard",children:c("pa.standard")}),(0,jn.jsx)(ra,{value:"detailed",children:c("pa.detailed")})]})]})]}),(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"text-sm font-medium text-foreground",children:c("pa.tone")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:c("pa.tone_desc",{name:n})})]}),(0,jn.jsxs)(aa,{value:r.override_tone||"auto",onValueChange:e=>a("override_tone",e),children:[(0,jn.jsx)(ea,{className:"w-32 h-8 text-xs",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"auto",children:c("pa.auto")}),(0,jn.jsx)(ra,{value:"empathetic",children:c("pa.empathetic")}),(0,jn.jsx)(ra,{value:"tactical",children:c("pa.tactical")})]})]})]}),(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsx)("p",{className:"text-sm font-medium text-foreground",children:c("pa.avatar")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:c("pa.avatar_desc",{name:n})}),(0,jn.jsxs)("div",{className:"flex gap-1.5 flex-wrap items-center",children:[(0,jn.jsx)("button",{type:"button",onClick:()=>a("selected_avatar",""),title:c("pa.use_default"),className:He("p-1 rounded-lg transition-colors",""===d?"bg-primary/20 ring-2 ring-primary":"hover:bg-muted"),children:(0,jn.jsx)(Or,{value:o,size:"2xl"})}),ro.filter(e=>e!==o).map(e=>(0,jn.jsx)("button",{type:"button",onClick:()=>a("selected_avatar",e),className:He("text-2xl p-1.5 rounded-lg transition-colors",d===e?"bg-primary/20 ring-2 ring-primary":"hover:bg-muted"),children:e},e)),l.map(e=>(0,jn.jsx)("button",{type:"button",onClick:()=>a("selected_avatar",e.url),title:e.label,className:He("p-1 rounded-lg transition-colors",d===e.url?"bg-primary/20 ring-2 ring-primary":"hover:bg-muted"),children:(0,jn.jsx)(Or,{value:e.url,size:"2xl"})},e.id))]})]})]})]}),(0,jn.jsx)(ja,{value:"learning",className:"py-2",children:i?(0,jn.jsx)(to,{projectId:i}):(0,jn.jsx)("p",{className:"text-xs text-muted-foreground text-center py-4",children:c("pa.unable_learning")})})]})]})})}var no={reminders_enabled:!0,follow_ups_enabled:!0,daily_greeting_enabled:!0,proactive_nudges_enabled:!0,preferred_personality:"friendly",break_reminders_enabled:!0,preferred_voice_gender:"male",selected_avatar:"",override_verbosity:"auto",override_tone:"auto",confirm_outward_actions:!0};var io=new Set;function oo(e){const{user:t}=$t(),r=t?.id,{t:a}=at(),s=(0,fn.useRef)(a);s.current=a;const[n,i]=(0,fn.useState)(no),[o,l]=(0,fn.useState)(!1),c=(0,fn.useRef)(Symbol("assistant-preferences")),d=(0,fn.useRef)({}),u=(0,fn.useRef)({}),m=(0,fn.useRef)(null),p=(0,fn.useRef)(null);return(0,fn.useEffect)(()=>
2{if(!e||!r)return;let t=!1,a=null;d.current={},l(!1);const s=async n=>{const{data:o,error:c}=await Lt.from("user_assistant_preferences").select("*").eq("user_id",r).eq("project_id",e).maybeSingle();if(!t){if(c)return Ge.error("[useAssistantPreferences] load failed",c,{projectId:e,attempt:n}),void(0===n&&(a=setTimeout(()=>{s(1)},2e3)));var u;i({...(u=o,u?{reminders_enabled:u.reminders_enabled??!0,follow_ups_enabled:u.follow_ups_enabled??!0,daily_greeting_enabled:u.daily_greeting_enabled??!0,proactive_nudges_enabled:u.proactive_nudges_enabled??!0,preferred_personality:u.preferred_personality||"friendly",break_reminders_enabled:u.break_reminders_enabled??!0,preferred_voice_gender:u.preferred_voice_gender||"male",selected_avatar:u.selected_avatar||"",override_verbosity:u.override_verbosity||"auto",override_tone:u.override_tone||"auto",confirm_outward_actions:u.confirm_outward_actions??!0}:{...no}),...d.current}),l(!0)}};return s(0),()=>{t=!0,a&&clearTimeout(a),m.current&&(clearTimeout(m.current),m.current=null,p.current?.())}},[e,r]),(0,fn.useEffect)(()=>{if(!e||!r)return;const t=(t,a,s,n)=>{if(t===c.current||a!==r||s!==e)return;d.current={...d.current,...n};const o={...u.current};for(const e of Object.keys(n))delete o[e];u.current=o,i(e=>({...e,...n}))};return io.add(t),()=>{io.delete(t)}},[e,r]),{preferences:n,loaded:o,updatePreference:(0,fn.useCallback)((t,a)=>{if(!e||!r)return;const n={[t]:a};i(e=>({...e,...n})),d.current={...d.current,...n},u.current={...u.current,...n},io.forEach(t=>t(c.current,r,e,n));const o=()=>{m.current=null;const t=u.current;if(0===Object.keys(t).length)return;u.current={};const a={user_id:r,project_id:e,...t};Lt.from("user_assistant_preferences").upsert(a,{onConflict:"user_id,project_id"}).then(({error:r})=>{r&&(Ge.error("[useAssistantPreferences] upsert failed",r,{projectId:e,fields:Object.keys(t)}),Ae.error(s.current("pa.preferences_save_failed")))})};p.current=o,m.current&&clearTimeout(m.current),m.current=setTimeout(o,400)},[e,r])}}function lo(e){const{user:t}=$t(),[r,a]=(0,fn.useState)(0),s=(0,fn.useCallback)(async()=>{if(!e||!t)return void a(0);const{count:r,error:s}=await Lt.from("personal_assistant_conversations").select("id",{count:"exact",head:!0}).eq("project_id",e).eq("user_id",t.id).eq("role","assistant").is("read_at",null);s?Ge.error("Error fetching unread PA count:",s):a(r??0)},[e,t]);return(0,fn.useEffect)(()=>{s()},[s]),(0,fn.useEffect)(()=>{if(!e||!t)return;let r=null;return(()=>{const a=Jt(`pa-unread-${e}-${t.id}`);r=Lt.channel(a).on("postgres_changes",{event:"*",schema:"public",table:"personal_assistant_conversations",filter:`user_id=eq.${t.id}`},t=>{const r=t.new||t.old;r?.project_id&&r.project_id!==e||s()}).subscribe()})(),()=>{r&&Lt.removeChannel(r)}},[e,t,s]),{unreadCount:r,refresh:s}}var co=e=>!!e&&(e.startsWith("dm_")||e.startsWith("gdm_")),uo=e=>e?e.startsWith("gdm_")?e.slice(4).split("_").filter(Boolean):e.startsWith("dm_")?e.slice(3).split("_").filter(Boolean):[]:[],mo=(e,t,r)=>!co(e)||!!t&&(!(!r||r!==t)||uo(e).includes(t)),po=(e,t)=>{if(!e.startsWith("dm_"))return e;const r=uo(e);return 2===r.length?`dm_${r.find(e=>e!==t)??r[0]}`:e},ho=(e,t)=>{if(!e.startsWith("dm_")||!t)return e;const r=e.slice(3);return r.includes("_")?e:Ke(t,r)},fo=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isNaN(t)?0:t};function go(e,t){const r=new Map;for(const a of e)r.set(a.id,a);for(const a of t)r.set(a.id,a);return[...r.values()].sort((e,t)=>fo(e.created_at)-fo(t.created_at))}var xo={projectId:null,users:new Map},_o=xo,bo=new Set;function jo(e){return bo.add(e),()=>{bo.delete(e)}}function vo(){return _o}var yo={NOTES:"Notes",OKRS:"OKRs",COMMUNICATION:"Chat",WHITEBOARD:"Whiteboard",DASHBOARD:"Dashboard",IDEATION:"Ideation",MARKET_RESEARCH:"Market Research",STRATEGY:"Strategy",PRODUCT:"Product",MARKETING:"Marketing",FINANCIALS:"Financials",ROADMAP:"Roadmap",TASKS:"Tasks",RISK:"Risk",TEAM:"Team"},wo=({open:e,onOpenChange:t,sourceModule:r,sourceContext:a,teamMembers:s,showDueDate:n=!1,onCreateTask:i})=>{const[o,l]=(0,fn.useState)(""),[c,d]=(0,fn.useState)(""),[u,m]=(0,fn.useState)("MEDIUM"),[p,h]=(0,fn.useState)(""),[f,g]=(0,fn.useState)(""),[x,_]=(0,fn.useState)(!1),b=(0,fn.useRef)(D()),j=(0,fn.useRef)(!1),v=yo[r]||r;(0,fn.useEffect)(()=>{e&&(b.current=D())},[e]),(0,fn.useEffect)(()=>
2{if(e&&a&&(d(`From ${v}:\n\n${a}`),!o&&"WHITEBOARD"===r)){const e=a.split("\n")[0]?.trim();e&&l(e.slice(0,80))}},[e,a,r]);const y=async()=>{if(o.trim()&&!j.current){j.current=!0,_(!0);try{if(!1===await i({id:b.current,title:o.trim(),description:c.trim(),priority:u,tags:[`from-${v.toLowerCase().replace(/\s+/g,"-")}`],assigneeId:p&&"unassigned"!==p?p:void 0,dueDate:f||void 0}))return;b.current=D(),l(""),d(""),m("MEDIUM"),h(""),g(""),t(!1)}catch(e){Ge.error("Quick task capture failed",e,{sourceModule:r}),Ae.error(dt("shared.quick_task_create_failed"))}finally{j.current=!1,_(!1)}}};return(0,jn.jsx)(xt,{open:e,onOpenChange:t,children:(0,jn.jsxs)(ht,{className:"sm:max-w-md",children:[(0,jn.jsx)(mt,{children:(0,jn.jsxs)(ft,{className:"flex items-center gap-2",children:[(0,jn.jsx)(me,{className:"w-4 h-4 text-amber-500"}),"Quick Task",(0,jn.jsxs)(Pr,{variant:"secondary",className:"text-xs font-normal",children:["from ",v]})]})}),(0,jn.jsxs)("div",{className:"space-y-3 py-2",children:[(0,jn.jsxs)("div",{className:"space-y-1",children:[(0,jn.jsx)(na,{htmlFor:"qt-title",children:"Title"}),(0,jn.jsx)(Et,{id:"qt-title",value:o,onChange:e=>l(e.target.value),placeholder:"What needs to be done?",autoFocus:!0,onKeyDown:e=>{"Enter"!==e.key||e.shiftKey||(e.preventDefault(),y())}})]}),(0,jn.jsxs)("div",{className:"space-y-1",children:[(0,jn.jsx)(na,{htmlFor:"qt-desc",children:"Description"}),(0,jn.jsx)(Hr,{id:"qt-desc",value:c,onChange:e=>d(e.target.value),placeholder:"Add details...",rows:3})]}),(0,jn.jsxs)("div",{className:s&&s.length>0?"grid grid-cols-2 gap-3":"space-y-1",children:[(0,jn.jsxs)("div",{className:"space-y-1",children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1",children:[(0,jn.jsx)(M,{className:"h-3 w-3"}),"Priority"]}),(0,jn.jsxs)(aa,{value:u,onValueChange:m,children:[(0,jn.jsx)(ea,{children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"HIGH",children:"ð´ High"}),(0,jn.jsx)(ra,{value:"MEDIUM",children:"ð¡ Medium"}),(0,jn.jsx)(ra,{value:"LOW",children:"ð¢ Low"})]})]})]}),s&&s.length>0&&(0,jn.jsxs)("div",{className:"space-y-1",children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1",children:[(0,jn.jsx)(Pe,{className:"h-3 w-3"}),"Assignee"]}),(0,jn.jsxs)(aa,{value:p,onValueChange:h,children:[(0,jn.jsx)(ea,{children:(0,jn.jsx)(Xr,{placeholder:"Select..."})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"unassigned",children:"Unassigned"}),s.map(e=>(0,jn.jsx)(ra,{value:e.id,children:e.name},e.id))]})]})]})]}),n&&(0,jn.jsxs)("div",{className:"space-y-1",children:[(0,jn.jsxs)(na,{htmlFor:"qt-due",className:"flex items-center gap-1",children:[(0,jn.jsx)(K,{className:"h-3 w-3"}),"Due Date"]}),(0,jn.jsx)(Et,{id:"qt-due",type:"date",value:f,onChange:e=>g(e.target.value)})]})]}),(0,jn.jsxs)(pt,{children:[(0,jn.jsx)(Ye,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),(0,jn.jsxs)(Ye,{onClick:y,disabled:!o.trim()||x,children:[(0,jn.jsx)(me,{className:"w-4 h-4 mr-1"}),x?"Creatingâ¦":"Create Task"]})]})]})})},No=["architecture","product","design","process","strategy","technical","hiring","budget"],ko=({open:e,onOpenChange:t,projectId:r,sourceMessageId:a,initialDecision:s="",initialContext:n=""})=>{const{t:i}=at(),o=ir(),[l,c]=(0,fn.useState)(s),[d,u]=(0,fn.useState)(n),[m,p]=(0,fn.useState)([]),[h,f]=(0,fn.useState)(""),[g,x]=(0,fn.useState)(!1),_=g||o,b=e=>{const t=e.toLowerCase().trim().slice(0,40);t&&!m.includes(t)&&m.length<10&&p([...m,t]),f("")};return(0,jn.jsx)(xt,{open:e,onOpenChange:t,children:(0,jn.jsxs)(ht,{className:"max-w-lg",children:[(0,jn.jsx)(mt,{children:(0,jn.jsxs)(ft,{className:"flex items-center gap-2",children:[(0,jn.jsx)(ve,{className:"w-5 h-5 text-primary"}),i("chat.log_decision_title")]})}),(0,jn.jsxs)("div",{className:"space-y-4 py-2",children:[o&&(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:i("permissions.view_only_hint")}),(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsx)(na,{htmlFor:"decision",children:i("chat.decision_label")}),(0,jn.jsx)(Hr,{id:"decision",value:l,onChange:e=>c(e.target.value),placeholder:i("chat.decision_ph"),className:"min-h-[80px]",maxLength:5e3,disabled:_})]}),(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsx)(na,{htmlFor:"context",children:i("chat.context_optional")}),(0,jn.jsx)(Hr,{id:"context",value:d,onChange:e=>u(e.target.value),placeholder:i("chat.context_ph"),className:"min-h-[60
2px]",maxLength:2e3,disabled:_})]}),(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsx)(na,{children:i("chat.tags")}),(0,jn.jsx)("div",{className:"flex flex-wrap gap-1.5 mb-2",children:m.map(e=>(0,jn.jsxs)(Pr,{variant:"secondary",className:"cursor-pointer hover:bg-destructive/20",onClick:()=>!_&&(e=>{p(m.filter(t=>t!==e))})(e),children:[e,(0,jn.jsx)(J,{className:"w-3 h-3 ml-1"})]},e))}),(0,jn.jsxs)("div",{className:"flex gap-2",children:[(0,jn.jsx)(Et,{value:h,onChange:e=>f(e.target.value),placeholder:i("chat.add_tag_ph"),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),b(h))},className:"flex-1",maxLength:40,disabled:_}),(0,jn.jsx)(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>b(h),disabled:!h.trim()||_,children:i("action.add")})]}),(0,jn.jsx)("div",{className:"flex flex-wrap gap-1 mt-2",children:No.filter(e=>!m.includes(e)).map(e=>(0,jn.jsxs)(Pr,{variant:"outline",className:"cursor-pointer hover:bg-muted",onClick:()=>!_&&b(e),children:[(0,jn.jsx)(ke,{className:"w-3 h-3 mr-1"}),i(`chat.tag_${e}`)]},e))})]}),a&&(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:i("chat.decision_linked_message")}),(0,jn.jsx)(So,{projectId:r,decisionText:l})]}),(0,jn.jsxs)(pt,{children:[(0,jn.jsx)(Ye,{variant:"outline",onClick:()=>t(!1),children:i("action.cancel")}),!o&&(0,jn.jsx)(Ye,{onClick:async()=>{if(!o)if(l.trim()){x(!0);try{const{data:{user:e}}=await Lt.auth.getUser();if(!e)return void Ae.error(i("chat.decision_sign_in"));const{error:s}=await Lt.from("project_decisions").insert({project_id:r,decided_by:e.id,decision:l.trim(),rationale:d.trim()||null,source:a?"chat":"manual",source_ref:a||null,decided_at:(new Date).toISOString(),tags:m});if(s)throw s;Ae.success(i("chat.decision_logged")),t(!1),c(""),u(""),p([])}catch(e){if(Ge.error("Error logging decision:",e),Yr(e,{projectId:r}))return;Ae.error(i("chat.decision_failed"))}finally{x(!1)}}else Ae.error(i("chat.decision_required"))},disabled:!l.trim()||g,children:g?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)(ce,{className:"w-4 h-4 mr-2 animate-spin"}),i("common.saving")]}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)(ve,{className:"w-4 h-4 mr-2"}),i("chat.log_decision_title")]})})]})]})})};function So({projectId:e,decisionText:t}){const{t:r}=at(),{formatDate:a}=ut(),[s,n]=fn.useState(null);return fn.useEffect(()=>{if(t.length<10)return void n(null);const s=setTimeout(async()=>{try{const s=t.toLowerCase().split(/\s+/).filter(e=>e.length>4).slice(0,5);if(0===s.length)return;const{data:i}=await Lt.from("meeting_recordings").select("title, summary, created_at").eq("project_id",e).eq("status","done").order("created_at",{ascending:!1}).limit(5);if(!i)return;const o=i.find(e=>{const t=`${e.title||""} ${e.summary||""}`.toLowerCase();return s.some(e=>t.includes(e))});n(o?{title:o.title||r("common.untitled"),date:a(o.created_at,"P")}:null)}catch{n(null)}},500);return()=>clearTimeout(s)},[t,e,a,r]),s?(0,jn.jsxs)("p",{className:"text-xs text-muted-foreground bg-muted/50 rounded-lg px-2 py-1.5",children:["ð ",r("chat.related_meeting",{title:s.title,date:s.date})]}):null}function Io({search:e,onSelect:t,onCreateTask:r,onCreatePoll:a,onMentionOKR:s,onSetReminder:n,onMentionTask:i,onGenerateSummary:o,onCreateNote:l,onLogDecision:d,onThreadToTask:u}){const{t:m}=at(),p=(0,fn.useMemo)(()=>{const t=[{id:"task",name:"/task",description:m("chat.cmd_task_desc"),icon:(0,jn.jsx)(ee,{className:"h-4 w-4"}),action:r||(()=>{})},{id:"mention-task",name:"/mention-task",description:m("chat.cmd_mention_task_desc"),icon:(0,jn.jsx)(F,{className:"h-4 w-4"}),action:i||(()=>{})},{id:"okr",name:"/okr",description:m("chat.cmd_okr_desc"),icon:(0,jn.jsx)(j,{className:"h-4 w-4"}),action:s},{id:"poll",name:"/poll",description:m("chat.cmd_poll_desc"),icon:(0,jn.jsx)(_,{className:"h-4 w-4"}),action:a},{id:"remind",name:"/remind",description:m("chat.cmd_remind_desc"),icon:(0,jn.jsx)($e,{className:"h-4 w-4"}),action:n||(()=>{})},{id:"summarize",name:"/summarize",description:m("chat.cmd_summarize_desc"),icon:(0,jn.jsx)(se,{className:"h-4 w-4"}),action:o||(()=>{})},{id:"note",name:"/note",description:m("chat.cmd_note_desc"),icon:(0,jn.jsx)(c,{className:"h-4 w-4"}),action:l||(()=>{})}
2,{id:"decision",name:"/decision",description:m("chat.cmd_decision_desc"),icon:(0,jn.jsx)(ve,{className:"h-4 w-4"}),action:d||(()=>{})},{id:"thread-to-task",name:"/thread-to-task",description:m("chat.cmd_thread_task_desc"),icon:(0,jn.jsx)(Ce,{className:"h-4 w-4"}),action:u||(()=>{})}].filter(e=>!("task"===e.id&&!r)&&(!("remind"===e.id&&!n)&&(!("mention-task"===e.id&&!i)&&(!("summarize"===e.id&&!o)&&(!("note"===e.id&&!l)&&(!("decision"===e.id&&!d)&&!("thread-to-task"===e.id&&!u))))))),p=e.toLowerCase();return t.filter(e=>e.name.toLowerCase().includes(p)||e.description.toLowerCase().includes(p))},[e,r,a,s,n,i,o,l,d,u,m]),[h,f]=(0,fn.useState)(0);(0,fn.useEffect)(()=>{f(0)},[e,p.length]);const g=fn.useRef(p);g.current=p;const x=fn.useRef(h);return x.current=h,(0,fn.useEffect)(()=>{const e=e=>{const r=g.current;if(0===r.length)return;const a=x.current;if("ArrowDown"===e.key)e.preventDefault(),f(e=>(e+1)%r.length);else if("ArrowUp"===e.key)e.preventDefault(),f(e=>(e-1+r.length)%r.length);else if("Enter"===e.key||"Tab"===e.key){e.preventDefault();const s=r[a];s&&(t(s),s.action())}};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[t]),(0,jn.jsx)(Pt,{className:"rounded-lg border shadow-md bg-popover",shouldFilter:!1,children:(0,jn.jsxs)(Mt,{children:[(0,jn.jsx)(Rt,{children:m("chat.no_commands_found")}),(0,jn.jsx)(Dt,{heading:m("chat.commands_group"),children:p.map((e,r)=>(0,jn.jsx)(Ot,{onSelect:()=>{t(e),e.action()},onMouseEnter:()=>f(r),className:He("cursor-pointer",r===h&&"bg-accent text-accent-foreground"),children:(0,jn.jsxs)("div",{className:"flex items-center gap-3",children:[(0,jn.jsx)("div",{className:"text-muted-foreground",children:e.icon}),(0,jn.jsxs)("div",{children:[(0,jn.jsx)("div",{className:"font-medium",children:e.name}),(0,jn.jsx)("div",{className:"text-xs text-muted-foreground",children:e.description})]})]})},e.id))})]})})}var Co={delete_task:{effect:"archive",itemType:"task"},delete_epic:{effect:"archive",itemType:"epic"},archive_tasks:{effect:"archive",itemType:"task_bulk"},delete_okr:{effect:"archive",itemType:"okr"},delete_whiteboard:{effect:"archive",itemType:"whiteboard"},delete_note:{effect:"trash",itemType:"note"},delete_drive_item:{effect:"trash",itemType:null},delete_risk:{effect:"delete",itemType:"risk"},delete_crm_record:{effect:"trash",itemType:null,effectByItemType:{crm_activity:"delete"}}},Eo={task:"chat.item_task",epic:"chat.item_epic",note:"chat.item_note",okr:"chat.item_okr",whiteboard:"chat.item_whiteboard",risk:"chat.item_risk",file:"chat.item_file",folder:"chat.item_folder",crm_deal:"chat.item_deal",crm_contact:"chat.item_contact",crm_organization:"chat.item_organization",crm_activity:"chat.item_activity"};function To(e){return e&&Object.prototype.hasOwnProperty.call(Eo,e)?Eo[e]:"chat.item_item"}function Ao(){return"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?crypto.randomUUID():`pc-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Do(e){return e&&"object"==typeof e&&!Array.isArray(e)?e:null}function Oo(e,t,r){const a=Do(t);if(!a||!a.requires_confirmation||"outward_action"===a.kind)return null;const s=Co[e];if(!s||!function(e){return Object.prototype.hasOwnProperty.call(Co,e)}(e))return null;const n=function(e){const t=Array.isArray(e.actionKeyboard)?e.actionKeyboard:[];for(const r of t)if(Array.isArray(r))for(const e of r){const t=Do(e);if(!t||"delete_confirm"!==t.kind)continue;const r=Do(t.payload);if(!r)continue;const a="string"==typeof r.tool_name?r.tool_name:"",s="string"==typeof r.confirmation_token?r.confirmation_token:"";if(a&&s)return{tool_name:a,tool_args:{...Do(r.tool_args)??{}},confirmation_token:s}}return null}(a);if(!n||n.tool_name!==e)return null;const i="string"==typeof a.confirmation_token?a.confirmation_token:"";if(i&&i!==n.confirmation_token)return null;const o=s.itemType??("string"==typeof a.item_type&&a.item_type?a.item_type:"item"),l=[a.item_title,a.item_name].find(e=>"string"==typeof e&&e.trim().length>0)??"",c="number"==typeof a.match_count?a.match_count:"number"==typeof a.child_count?a.child_count:void 0,d=Array.isArray(a.sample_titles)?a.sample_titles.filter(e=>"string"==typeof e).slice(0,5):void 0,{confirmation_token:u,...m}=n.tool_args;return{id:Ao(),tool_name:e,tool_args:m,confirmation_token:n.confirmation_token,effect:s.effectByItemType&&Object.prototype.hasOwnProperty.call(s.effectByItemType,o)?s.effectByItemType[o]:s.effect,item_type:o,item_title:l,item_count:c,sample_titles:d,project_id:r.projectId,thread_id:r.threadId,created_at:r.now??Date.now()}}function Ro(e,t){const r=Do(e);if(!r||!r.requires_confirmation||"outward_action"!==r.kind)return null;const a="string"==typeof r.tool_name?r.tool_name:"";if(!a)return null;const s=Do(r.preview);return{id:Ao(),toolName:a,args:{...Do(r.tool_args)??{}},preview:{title:"string"==typeof s?.title&&s.title?s.title:a,body:"string"==typeof s?.body?s.body:"",..."string"==typeof s?.channel&&s.channel?{channel:s.channel}:{}}
2,threadId:t.threadId,created_at:t.now??Date.now()}}function Mo(e,t){const r=`${t.toolName}:${JSON.stringify(t.args)}`;return e.some(e=>(e.threadId??null)===(t.threadId??null)&&`${e.toolName}:${JSON.stringify(e.args)}`===r)?e:[...e,t]}function Po(e,t){return void 0===e||t-e<54e4}function Lo(e,t,r,a=Date.now()){return e.find(e=>(t(e)??null)===(r??null)&&Po(e.created_at,a))??null}function Uo(e,t,r,a=Date.now()){return e.filter(e=>(t(e)??null)===(r??null)&&Po(e.created_at,a)).length}function $o(e,t){return t&&e.some(e=>e.id===t)?e.filter(e=>e.id!==t):e}var Fo={delete_task:"tasks-updated-externally",delete_epic:"tasks-updated-externally",archive_tasks:"tasks-updated-externally",delete_note:"notes-updated-externally",delete_okr:"okrs-updated-externally",delete_whiteboard:"whiteboards-updated-externally",delete_crm_record:"crm-updated-externally"};function Wo(){try{return"de"===localStorage.getItem("1tab:language")?"de":"en"}catch{return"en"}}var Ko={};function Ho(e,t){const r=Wo(),a=Ko[r]?.[e]||Ko.en?.[e]||e;return t?a.replace(/\{(\w+)\}/g,(e,r)=>Object.prototype.hasOwnProperty.call(t,r)?String(t[r]):e):a}async function qo(e){await async function(){const e=Wo(),t=[];Ko.en||t.push(nt("en").then(e=>{Ko.en=e})),Ko[e]||t.push(nt(e).then(t=>{Ko[e]=t})),await Promise.allSettled(t)}();const t=Ho;try{const{data:r,error:a}=await Lt.functions.invoke("personal-assistant",{body:{type:"execute_tool",projectId:e.project_id,toolName:e.tool_name,args:{...e.tool_args,confirmation_token:e.confirmation_token}},headers:{"Idempotency-Key":"undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?`pa-delete-${crypto.randomUUID()}`:`pa-delete-${Date.now()}-${Math.random().toString(36).slice(2,12)}`}});if(a){const e=await Mr(a);return Ae.error(t("chat.confirm_action_failed",{message:e})),!1}const s=r&&"object"==typeof r?r:null;if(!s||s.error||!1===s.success||s.requires_confirmation){const e="string"==typeof s?.error&&s.error?s.error:t("chat.confirm_action_unknown");return Ae.error(t("chat.confirm_action_failed",{message:e})),!1}const n=Fo[e.tool_name];return n&&window.dispatchEvent(new Event(n)),Ae.success(function(e,t){const r=t(To(e.item_type));return"task_bulk"===e.item_type?t("chat.items_archived",{count:e.item_count??0}):"archive"===e.effect?t("chat.item_archived",{type:r}):"trash"===e.effect?t("chat.item_trashed",{type:r}):t("chat.item_deleted",{type:r})}(e,t)),!0}catch(r){return Ge.error("Assistant delete confirmation failed",r,{tool:e.tool_name}),Ae.error(t("chat.confirm_action_failed",{message:r instanceof Error?r.message:String(r)})),!1}}function zo({pending:e,onClose:t,onDeleted:r}){const{t:a}=at(),s=(0,fn.useRef)(!1),n=e?function(e,t){const r=t(To(e.item_type)),a=e.item_title||"";return"task_bulk"===e.item_type?{title:t("chat.archive_bulk_title",{count:e.item_count??e.sample_titles?.length??0}),description:t("chat.archive_bulk_desc"),confirmLabel:t("action.archive")}:"archive"===e.effect?{title:t("chat.archive_item_title",{type:r}),description:"epic"===e.item_type&&(e.item_count??0)>0?t("chat.archive_epic_desc",{title:a,count:e.item_count??0}):t("chat.archive_item_desc",{title:a}),confirmLabel:t("action.archive")}:"trash"===e.effect?{title:t("chat.trash_item_title",{type:r}),description:t("chat.trash_item_desc",{title:a}),confirmLabel:t("chat.move_to_trash")}:{title:t("chat.delete_item_title",{type:r}),description:t("chat.delete_item_desc",{title:a}),confirmLabel:t("action.delete")}}(e,a):null,i="delete"===e?.effect;return(0,jn.jsx)(Ct,{open:!!e,onOpenChange:e=>{e||t()},children:(0,jn.jsxs)(wt,{children:[(0,jn.jsxs)(It,{children:[(0,jn.jsx)(yt,{children:n?.title}),(0,jn.jsx)(vt,{children:n?.description})]}),"task_bulk"===e?.item_type&&(e.sample_titles?.length??0)>0&&(0,jn.jsx)("ul",{className:"rounded-md border border-border bg-muted/40 p-2 text-sm text-foreground list-disc pl-6 max-h-40 overflow-y-auto",children:e.sample_titles.map((t,r)=>(0,jn.jsx)("li",{children:t},`${e.id}-sample-${r}`))}),(0,jn.jsxs)(kt,{children:[(0,jn.jsx)(St,{children:a("action.cancel")}),(0,jn.jsx)(Nt,{onClick:()=>{(async()=>{if(e&&!s.current){s.current=!0;try{await qo(e)&&r?.()}finally{s.current=!1}}})()},className:i?"bg-destructive text-destructive-foreground hover:bg-destructive/90":void 0,children:n?.confirmLabel})]})]})})}var Vo="I'm trying to put that on the whiteboard now. I'll update you when it's ready.";async function Bo(e){if(!e)return null;try{const{data:t,error:r}=await Lt.from("projects").select("boards").eq("id",e).maybeSingle();if(r||!t)return null;const a=(t.boards||[])[0];return a?{boardId:a.id,statuses:Array.isArray(a.statuses)?a.statuses:[]}:null}catch{return null}}async function Go(e,t){try{const{data:r,error:a}=await Lt.functions.invoke("personal-assistant",{body:{type:"execute_tool",projectId:e,toolName:"undo_last",args:{undo_id:t}}});if(a)return void Ae.error(dt("pa.toast_undo_failed",{reason:a.message}));if(r?.error)return void Ae.error(dt("pa.toast_undo_failed",{reason:String(r.error)}));Ae.success(r?.summary||"â¶ Reverted")}catch(r){Ae.error(dt("pa.toast_undo_failed",{reason:r instanceof Error?r.message:String(r)}))}}function Yo(e,t,r){const{user:a}=$t(),[s,n]=(0,fn.useState)([]),[i,o]=(0,fn.useState)(!0),[l,c]=(0,fn.useState)([]),[d,u]=(0,fn.useState)([]),m=(0,fn.useRef)(!1),p=(0,fn.useRef)(r??null);p.current=r??null;const[h,f]=(0,fn.useState)(!1),[g,x]=(0,fn.useState)(null),[_,b]=(0,fn.useState)(null),[j,v]=(0,fn.useState)(!1),[y,w]=(0,fn.useState)({}
2),[N,k]=(0,fn.useState)({display_name:"Assad",avatar_emoji:"ð¤",personality:"friendly",greeting_message:"Good morning! Ready to make today productive?",avatar_options:[]}),S=(0,fn.useRef)(null),I=(0,fn.useRef)(!1),C=(0,fn.useRef)(t);C.current=t,(0,fn.useEffect)(()=>()=>{S.current?.abort(),S.current=null,I.current=!1},[]),(0,fn.useEffect)(()=>{if(!e||!a)return;(async()=>{const[t,r]=await Promise.all([Lt.from("project_personal_assistant_config").select("enabled, daily_greeting, proactive_nudges, activated_user_ids").eq("project_id",e).maybeSingle(),Lt.from("app_settings").select("value").eq("key","personal_assistant_config").maybeSingle()]);if(t.error&&Ge.error("Failed to load PA project config",t.error,{projectId:e}),r.error&&Ge.error("Failed to load PA settings",r.error,{projectId:e}),t.data&&b(t.data),v(!0),r.data?.value){const e=r.data.value,t=(Array.isArray(e.avatar_options)?e.avatar_options:[]).filter(e=>e&&"string"==typeof e.url&&e.url.length>0).map(e=>({id:String(e.id||""),label:String(e.label||""),url:String(e.url)}));k({display_name:e.display_name||"Assad",avatar_emoji:e.avatar_emoji||"ð¤",personality:e.personality||"friendly",greeting_message:e.greeting_message||"Good morning! Ready to make today productive?",avatar_options:t})}})()},[e,a]);const E=j&&(null===_||_.enabled&&(!_.activated_user_ids||_.activated_user_ids.includes(a?.id||""))),[T,A]=(0,fn.useState)(!1),D=(0,fn.useCallback)(async(t={})=>{if(!e||!a)return{rows:[],hasMoreOlder:!1};let s=Lt.from("personal_assistant_conversations").select("id, role, content, created_at, thread_id, pinned, is_private, read_at, metadata").eq("project_id",e).eq("user_id",a.id);s=r?s.eq("thread_id",r):s.is("thread_id",null),t.before&&(s=s.lt("created_at",t.before));const{data:n,error:i}=await s.order("created_at",{ascending:!1}).limit(101);if(i)return Ge.error("Failed to load PA conversation messages",i,{projectId:e,activeThreadId:r}),{rows:[],hasMoreOlder:!1,error:!0};const o=n||[];return{rows:o.slice(0,100).reverse(),hasMoreOlder:o.length>100}},[e,a,r]),O=(0,fn.useCallback)(async e=>{if(!a||0===e.length)return;const{data:t,error:r}=await Lt.from("pa_message_feedback").select("message_id, rating").eq("user_id",a.id).in("message_id",e);r?Ge.error("Failed to load PA feedback",r):t&&w(e=>{const r={...e};for(const a of t)r[a.message_id]=a.rating;return r})},[a]),R=(0,fn.useCallback)(async()=>{if(!e||!a)return;if(!j)return;if(!E)return void o(!1);o(!0);const{rows:t,hasMoreOlder:r,error:s}=await D();A(r),n(t),o(!1),s&&Ae.error(dt("pa.toast_load_failed")),O(t.filter(e=>"assistant"===e.role).map(e=>e.id))},[e,a,E,j,D,O]);(0,fn.useEffect)(()=>{R()},[R]),(0,fn.useEffect)(()=>{if(!e||!a||!E)return;const t=Lt.channel(Jt(`pa-conversation-${e}-${a.id}`)).on("postgres_changes",{event:"INSERT",schema:"public",table:"personal_assistant_conversations",filter:`user_id=eq.${a.id}`},t=>{if(I.current)return;const r=t.new;r.project_id&&r.project_id!==e||(r.thread_id??null)===(p.current??null)&&n(e=>e.some(e=>e.id===r.id)?e:[...e,r])}).subscribe();return()=>{Lt.removeChannel(t)}},[e,a,E]);const M=(0,fn.useCallback)(async()=>{if(I.current)return;const{rows:e,hasMoreOlder:t}=await D();A(t),n(e)},[D]),P=(0,fn.useCallback)(async(t,r="chat",s,i,o)=>{if(!e||!a||I.current)return!1;if("undefined"!=typeof navigator&&!1===navigator.onLine)return Ae.error(dt("pa.toast_offline")),!1;I.current=!0;const l=void 0!==o?o??null:p.current??null,d=()=>(p.current??null)===l;let m=!1,h=!1;const g="briefing"===r?"âï¸ Brief me for today":"prepare_meeting"===r?"ð Prepare me for my next meeting":"standup"===r?"ð Generate my standup update":"end_of_day"===r?"ð End of day review":"weekly_plan"===r?"ð
Plan my week":t,_="chat"===r&&/\b(whiteboard|draw\s+(a|on|the|me)|diagram|flowchart|mind.?map|org.?chart|wireframe|sketch\s+(a|me|the|it))\b/i.test(t),b=/\b(note|notes|task|tasks|team\s+chat|chat|calendar|goal|goals|okr)\b/i.test(t),j=_&&!b;let v=j?Vo:"";const y=crypto.randomUUID(),w={id:crypto.randomUUID(),role:"user",content:g,created_at:(new Date).toISOString(),thread_id:l};if(n(e=>{if(!d())return e;const t=[...e,w];
2return j&&t.push({id:y,role:"assistant",content:v,created_at:(new Date).toISOString()}),t}),f(!0),x("briefing"===r?"Preparing your briefing...":"prepare_meeting"===r?"Gathering meeting context...":"standup"===r?"Checking your tasks for standup...":"end_of_day"===r?"Reviewing your day...":"weekly_plan"===r?"Building your weekly plan...":null),j&&Ae.loading(dt("pa.toast_whiteboard_progress"),{id:"wb-chat-progress"}),S.current)try{S.current.abort()}catch{}const N=new AbortController;S.current=N;let k=null,E=!1;const T=()=>{k&&clearTimeout(k),k=setTimeout(()=>{E=!0;try{N.abort()}catch{}},6e4)};let A=!1;const D=async t=>{if(A||!t.trim())return;A=!0;const{error:r}=await Lt.from("personal_assistant_conversations").insert({id:y,project_id:e,user_id:a.id,role:"assistant",content:t,thread_id:l});r&&(Ge.error("Failed to persist assistant message:",r),Ae.error(dt("pa.toast_reply_not_saved")))};try{let a;const{data:o}=await Lt.from("team_chat_messages_decrypted").select("id, content, channel, user_id, created_at, is_bot, bot_name").eq("project_id",e).order("created_at",{ascending:!1}).limit(20);if(o&&o.length>0){const e=[...o].reverse().reduce((e,t)=>{const r=t.content;if(!r)return e;const a=t,s=a.is_bot?a.bot_name||"Bot":"User";return e.push(`[${t.channel}] ${s}: ${r.slice(0,120)}`),e},[]);e.length>0&&(a=e.join("\n"))}const p=await Zi()||"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVvdnd5ZWN1cHB3bHhzaWNtcm5vIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTU2MzEsImV4cCI6MjA5MDQ3MTYzMX0.dFQPraCGmk38oJFH8AUUMEdXRR7a6qlnUGFJpv41f7c";T();const h=await fetch("https://eovwyecuppwlxsicmrno.supabase.co/functions/v1/personal-assistant",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({type:r,projectId:e,message:t,chatContext:a,screenshot:s,userPreferences:i||C.current,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone||void 0,thread_id:l||void 0,boardConfig:await Bo(e)}),signal:N.signal});if(!h.ok){const e=await h.json().catch(()=>({error:"Unknown error"}));return 429===h.status?Ae.error(dt("pa.toast_rate_limited")):402===h.status?Ae.error(dt("pa.toast_insufficient_credits")):401===h.status||403===h.status?(await Lt.auth.refreshSession().catch(()=>{}),Ae.error(e.error||"Session expired â try again.")):Ae.error(e.error||"Failed to get response"),n(e=>e.filter(e=>e.id!==w.id&&e.id!==y)),!1}if(m=!0,(h.headers.get("Content-Type")||"").includes("application/json")){const e=await h.json().catch(()=>null),t="string"==typeof e?.text?e.text.trim():"";return A=!0,t&&d()&&n(e=>e.some(e=>e.id===y)?e.map(e=>e.id===y?{...e,content:t}:e):[...e,{id:y,role:"assistant",content:t,created_at:(new Date).toISOString(),thread_id:l}]),!0}if(!h.body)throw new Error("No response body");const f=h.body.getReader(),g=new TextDecoder;let _="",b=!1,j=null;const k=()=>{j=null,d()&&n(e=>{const t=e.findIndex(e=>e.id===y);return-1!==t?e.map((e,r)=>r===t?{...e,content:v}:e):[...e,{id:y,role:"assistant",content:v,created_at:(new Date).toISOString(),thread_id:l}]})};for(;!b;){const{done:t,value:r}=await f.read();if(t){if(_+=g.decode(),!_.trim())break;_+="\n",b=!0}else T(),_+=g.decode(r,{stream:!0});let a;for(;-1!==(a=_.indexOf("\n"));){let t=_.slice(0,a);if(_=_.slice(a+1),t.endsWith("\r")&&(t=t.slice(0,-1)),t.startsWith(":")||""===t.trim())continue;if(!t.startsWith("data: "))continue;const r=t.slice(6).trim();if("[DONE]"===r){b=!0;break}try{const t=JSON.parse(r);if(t.__status){x(t.__status);continue}if(t.error){Ae.dismiss("pa-tool-progress"),Ae.dismiss("wb-chat-progress"),Ae.error(t.error,{duration:4e3}),x(null);continue}if(t.__toolStart){const e={send_chat_message:"ð¬ Sending messageâ¦",create_note:"ð Writing your noteâ¦",update_note:"ð Updating your noteâ¦",create_task:"ð Creating taskâ¦",update_task:"ð Updating taskâ¦",complete_task:"â
Completing taskâ¦",create_okr:"ð¯ Creating OKRâ¦",update_okr_progress:"ð¯ Updating OKRâ¦",create_reminder:"â° Setting reminderâ¦",draw_on_whiteboard:"ð¨ Drawing on whiteboard⦠(~15â30s)",create_whiteboard:"ð¨ Creating whiteboardâ¦",open_whiteboard:"ð¨ Opening whiteboardâ¦",create_calendar_event:"ð
Scheduling eventâ¦",navigate_module:"ð Navigatingâ¦",create_crm_contact:"ð¤ Adding contactâ¦",create_crm_deal:"ð¼ Creating dealâ¦",update_crm_deal:"ð¼ Updating dealâ¦",update_crm_deal_stage:"ð¼ Moving deal stageâ¦",update_crm_contact:"ð¤ Updating contactâ¦",log_crm_activity:"ð Logging activityâ¦",list_crm_deals:"ð¼ Looking up dealsâ¦",list_crm_contacts:"ð¤ Looking up contactsâ¦",list_crm_organizations:"ð¢ Looking up companiesâ¦",list_crm_activities:"ð Pulling activity feedâ¦",find_stale_deals:"â³ Finding stale dealsâ¦",get_crm_forecast:"ð Running forecastâ¦",get_crm_stats:"ð Crunching CRM numbersâ¦",get_crm_record_detail
2:"ð Reading CRM recordâ¦",get_pipeline_summary:"ð Summarizing pipelineâ¦",delete_crm_record:"ðï¸ Removing CRM recordâ¦",summarize_crm_to_note:"ð Saving CRM summary as a noteâ¦",post_crm_summary_to_chat:"ð¬ Posting CRM updateâ¦"}[t.__toolStart.name];e&&Ae.loading(e,{id:"pa-tool-progress",duration:6e4});continue}if(t.__toolResults){const r={create_task:"ð Task created",update_task:"ð Task updated",complete_task:"â
Task completed",create_note:"ð Note saved",update_note:"ð Note updated",send_chat_message:"ð¬ Message sent",create_calendar_event:"ð
Event scheduled",create_okr:"ð¯ OKR created",update_okr_progress:"ð¯ OKR updated",create_reminder:"â° Reminder set",draw_on_whiteboard:"ð¨ Whiteboard updated",create_whiteboard:"ð¨ Whiteboard created",open_whiteboard:"ð¨ Opening whiteboard",navigate_module:"ð Navigating",create_crm_contact:"ð¤ Contact added",create_crm_deal:"ð¼ Deal created",update_crm_deal:"ð¼ Deal updated",update_crm_deal_stage:"ð¼ Stage changed",update_crm_contact:"ð¤ Contact updated",log_crm_activity:"ð Activity logged",summarize_crm_to_note:"ð CRM summary saved as a note",post_crm_summary_to_chat:"ð¬ CRM update posted"},a={create_task:"tasks-updated-externally",update_task:"tasks-updated-externally",complete_task:"tasks-updated-externally",create_note:"notes-updated-externally",update_note:"notes-updated-externally",create_calendar_event:"calendar-event-created",create_okr:"okrs-updated-externally",update_okr_progress:"okrs-updated-externally",draw_on_whiteboard:"whiteboards-updated-externally",create_whiteboard:"whiteboards-updated-externally",send_chat_message:"chat-message-sent-externally",post_crm_summary_to_chat:"chat-message-sent-externally",summarize_crm_to_note:"notes-updated-externally",create_crm_contact:"crm-updated-externally",create_crm_deal:"crm-updated-externally",update_crm_deal:"crm-updated-externally",update_crm_deal_stage:"crm-updated-externally",update_crm_contact:"crm-updated-externally",log_crm_activity:"crm-updated-externally"};for(const s of t.__toolResults)try{const t=JSON.parse(s.result);if(t.requires_confirmation&&"outward_action"===t.kind){Ae.dismiss("pa-tool-progress");const e=Ro(t,{threadId:l});e&&u(t=>Mo(t,e));continue}if(t.requires_confirmation){Ae.dismiss("pa-tool-progress");const r=Oo(s.name,t,{projectId:e,threadId:l});r&&c(e=>{return a=r,(t=e).some(e=>e.confirmation_token===a.confirmation_token)?t:[...t,a];var t,a});continue}if(Ae.dismiss("pa-tool-progress"),t.success){if("draw_on_whiteboard"!==s.name&&"create_whiteboard"!==s.name&&"open_whiteboard"!==s.name||!t.whiteboard_id){Ae.dismiss("wb-chat-progress");let a=r[s.name]||"â Done";"send_chat_message"===s.name&&t.channel&&!t.isDM?a=`ð¬ Message sent in #${t.channel}`:"send_chat_message"===s.name&&t.isDM&&(a="ð¬ DM sent");const n=s.undoId,i=!!s.hasInverse;Ae(a,n&&i?{duration:8e3,className:"text-xs",action:{label:"â¶ Undo",onClick:()=>Go(e,n)}}:{duration:3e3,className:"text-xs"})}else{const e=t.whiteboard_name?`ð¨ Drawing ready on "${t.whiteboard_name}"`:"ð¨ Whiteboard ready!";Ae.success(e,{id:"wb-chat-progress",duration:4e3})}const n=a[s.name];n&&window.dispatchEvent(new Event(n)),t.whiteboard_id&&Ci(t.whiteboard_id),t.navigate_to&&window.dispatchEvent(new CustomEvent("navigate-to-module",{detail:{module:t.navigate_to,channel:"COMMUNICATION"===t.navigate_to&&t.channel||void 0}})),t.whiteboard_id&&window.dispatchEvent(new CustomEvent("select-whiteboard",{detail:{whiteboardId:t.whiteboard_id}}))}else t.error&&(Ae.dismiss("wb-chat-progress"),Ae.error(dt("pa.toast_action_failed",{reason:String(t.error)}),{duration:3e3}))}catch{}continue}const a=t.choices?.[0]?.delta?.content;a&&(v===Vo&&a.trim()&&(v+="\n\n"),v+=a,x(null),null===j&&(j=requestAnimationFrame(k)))}catch(O){Ge.error("Skipping malformed PA SSE frame",O,{line:t.slice(0,200)});continue}}}null!==j&&(cancelAnimationFrame(j),j=null),v.trim()||(v="I couldn't generate a reply this time â try rephrasing or asking again."),k(),await D(v)}catch(R){"AbortError"===(R instanceof Error?R.name:"")?(h=!0,await D(v),E&&Ae.error(dt("pa.toast_stopped_responding"))):(Ge.error("Personal assistant error:",R),Ae.error(dt("pa.toast_communication_failed")),m?v===Vo&&n(e=>e.filter(e=>e.id!==y)):n(e=>e.filter(e=>e.id!==w.id&&e.id!==y))),Ae.dismiss("wb-chat-progress"),Ae.dismiss("pa-tool-progress")}finally{k&&(clearTimeout(k),k=null),Ae.dismiss("wb-chat-progress"),Ae.dismiss("pa-tool-progress"),f(!1),x(null),S.current=null,I.current=!1}return m||h},[e,a]),L=(0,fn.useRef)(!1);(0,fn.useEffect)(()=>
2{if(i||L.current)return;if(!E)return;if(!C.current?.daily_greeting_enabled)return;const t=(new Date).toDateString(),r=`1tab_auto_brief_${e}_${a?.id}`;if(localStorage.getItem(r)===t)return;const s=(new Date).getHours();if(s<6||s>=13)return;L.current=!0,localStorage.setItem(r,t);const n=setTimeout(()=>{P("","briefing")},1e3);return()=>clearTimeout(n)},[i,E,e,a?.id,P]);const U=(0,fn.useCallback)(async()=>{if(!e||!a)return;let t=Lt.from("personal_assistant_conversations").delete().eq("project_id",e).eq("user_id",a.id);t=r?t.eq("thread_id",r):t.is("thread_id",null);const{error:s}=await t;if(s)return Ge.error("Failed to clear PA conversation",s,{projectId:e,activeThreadId:r}),void Ae.error(dt("pa.toast_clear_failed"));n([]),Ae.success(dt("pa.toast_cleared"))},[e,a,r]),$=(0,fn.useCallback)(()=>{S.current?.abort()},[]),F=(0,fn.useCallback)(async(t,r,s,n)=>{if(!e||!a)return;w(e=>({...e,[t]:r}));const{error:i}=await Lt.from("pa_message_feedback").upsert({message_id:t,project_id:e,user_id:a.id,rating:r,reason:"down"===r?s??null:null,note:"down"===r&&n?.trim()||null},{onConflict:"message_id,user_id"});i&&Ge.error("Feedback error:",i)},[e,a]),W=(0,fn.useMemo)(()=>Lo(l,e=>e.thread_id,r??null),[l,r]),K=(0,fn.useMemo)(()=>Uo(l,e=>e.thread_id,r??null),[l,r]),H=(0,fn.useMemo)(()=>Lo(d,e=>e.threadId,r??null),[d,r]),q=(0,fn.useMemo)(()=>Uo(d,e=>e.threadId,r??null),[d,r]),z=(0,fn.useCallback)(async()=>{const e=W;e&&(c(t=>$o(t,e.id)),await qo(e))},[W]),V=(0,fn.useCallback)(()=>{const e=W?.id;e&&c(t=>$o(t,e))},[W]),B=(0,fn.useCallback)(async()=>{const t=H;if(t&&e&&(t.threadId??null)===(p.current??null)&&!m.current){m.current=!0,u(e=>$o(e,t.id)),Ae.loading(dt("pa.toast_sending"),{id:"pa-confirm-action"});try{const{data:a,error:s}=await Lt.functions.invoke("personal-assistant",{body:{type:"execute_tool",projectId:e,toolName:t.toolName,args:t.args,confirmed:!0},headers:{"Idempotency-Key":(r="pa-confirm","undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID?`${r}-${crypto.randomUUID()}`:`${r}-${Date.now()}-${Math.random().toString(36).slice(2,12)}`)}});if(s||a&&(a.error||!1===a.success)){const e=s?await Mr(s):String(a?.error||"unknown error");return Ae.error(dt("pa.toast_complete_failed",{reason:e}),{id:"pa-confirm-action"}),void u(e=>e.some(e=>e.id===t.id)?e:[t,...e])}Ae.success({send_chat_message:"ð¬ Message sent",post_crm_summary_to_chat:"ð¬ CRM update posted",update_crm_deal_stage:"ð¼ Deal stage changed",create_calendar_event:"ð
Event scheduled"}[t.toolName]||"â Done",{id:"pa-confirm-action"});const n={send_chat_message:"chat-message-sent-externally",post_crm_summary_to_chat:"chat-message-sent-externally",update_crm_deal_stage:"crm-updated-externally",create_calendar_event:"calendar-event-created"}[t.toolName];n&&window.dispatchEvent(new Event(n))}catch(a){Ae.error(dt("pa.toast_complete_failed",{reason:a instanceof Error?a.message:String(a)}),{id:"pa-confirm-action"}),u(e=>e.some(e=>e.id===t.id)?e:[t,...e])}finally{m.current=!1}var r}},[H,e]),G=(0,fn.useCallback)(()=>{const e=H?.id;e&&u(t=>$o(t,e))},[H]);(0,fn.useEffect)(()=>{u([]),c([])},[e]);const Y=(0,fn.useCallback)(async t=>{if(!a||!e||0===t.length)return;const r=(new Date).toISOString();n(e=>e.map(e=>t.includes(e.id)&&!e.read_at?{...e,read_at:r}:e));const{error:s}=await Lt.from("personal_assistant_conversations").update({read_at:r}).in("id",t).eq("user_id",a.id).is("read_at",null);s&&(Ge.error("Failed to mark PA messages read:",s),n(e=>e.map(e=>t.includes(e.id)&&e.read_at===r?{...e,read_at:null}:e)))},[a,e]),[J,Q]=(0,fn.useState)(!1),Z=(0,fn.useCallback)(async()=>{if(J||!T)return;const e=s[0]?.created_at;if(!e)return;Q(!0);const{rows:t,hasMoreOlder:r}=await D({before:e});A(r),n(e=>{const r=new Set(e.map(e=>e.id));return[...t.filter(e=>!r.has(e.id)),...e]}),Q(!1),O(t.filter(e=>"assistant"===e.role).map(e=>e.id))},[D,s,J,T,O]),X=(0,fn.useCallback)(async(t,r)=>{if(!a||!e)return;n(e=>e.map(e=>e.id===t?{...e,pinned:r}:e));const{error:s}=await Lt.from("personal_assistant_conversations").update({pinned:r}).eq("id",t).eq("user_id",a.id);s&&(n(e=>e.map(e=>e.id===t?{...e,pinned:!r}:e)),Ae.error(dt(r?"pa.toast_pin_failed":"pa.toast_unpin_failed")))},[a,e]),ee=(0,fn.useCallback)(e=>{n(t=>[...t,{id:crypto.randomUUID(),role:"assistant",content:e,created_at:(new Date).toISOString(),metadata:{ephemeral:!0}}])},[]);return{messages:s,loading:i,streaming:h,statusText:g,isAvailable:!!E,config:_,settings:N,feedbackMap:y,sendMessage:P,clearHistory:U,stopStreaming:$,refreshMessages:M,submitFeedback:F,appendLocalAssistantMessage:ee,togglePin:X,pendingDelete:W,pendingDeleteCount:K,confirmDelete:z,cancelDelete:V,pendingConfirm:H,pendingConfirmCount:q,confirmOutwardAction:B,cancelConfirm:G,hasMoreOlder:T,loadingOlder:J,loadOlderMessages:Z,markMessagesRead:Y}}var Jo=[{re:/\b(\d+)\s+overdue\s+tasks?\b/i,build:e=>({kind:"tasks_overdue",label:`${e[1]} overdue`,count:Number(e[1])})},{re:/\b(\d+)\s+tasks?\s+due\s+today\b/i,build:e=>({kind:"tasks_due_today",label:`${e[1]} due today`,count:Number(e[1])})},{re:/\b(\d+)\s+open\s+tasks?\b/i,build:e=>({kind:"tasks_open",label:`${e[1]} open`,count:Number(e[1])})},{re:/\b(\d+)\s+(?:recent\s+)?meetings?\b/i,build:e=>({kind:"meetings",label:`${e[1]} meetings`,count:Number(e[1])})},{re:/\b(\d+)\s+OKRs?\b/i,build:e=>({kind:"okrs",label:`${e[1]} OKRs`,count:Number(e[1])})},{re:/\b(\d+)\s+(?:open\s+)?commitments?\b/i,build:e=>({kind:"commitments",label:`${e[1]} commitments`,count:Number(e[1])})}],Qo=[{re:/\brisk(?:\s+radar)?\b/i,module:jt.RISK,label:"Risks"},{re:/\bwhiteboard\b/i,module:jt.WHITEBOARD,label:"Whiteboard"},{re:/\bpitch\s+deck\b/i,module:jt.PITCH_DECK,label:"Pitch deck"},{re:/\bpipeline\b|\bCRM\b/i,module:jt.CRM,label:"CRM"}];function Zo(e){switch(e.kind){case"tasks_overdue":case"tasks_due_today":case"tasks_open":return jt.TASKS;case"meetings":return jt.MEETINGS;case"okrs":return jt.OKRS;case"module":return e.module;default:return null}}var Xo=1024;var el={success:{labelKey:"pa.audit_success",icon:N,cls:"text-emerald-600 dark:text-emerald-400"},error:{labelKey:"pa.audit_error",icon:C,cls:"text-red-600 dark:text-red-400"},requires_confirmation:{labelKey:"pa.audit_awaiting_confirmation",icon:Ue,cls:"text-amber-600 dar
2k:text-amber-400"},forbidden:{labelKey:"pa.audit_forbidden",icon:l,cls:"text-muted-foreground"}};function tl(e,t){const r=Date.now()-new Date(e).getTime();return r<6e4?t("pa.audit_just_now"):r<36e5?t("pa.audit_minutes_ago",{count:Math.floor(r/6e4)}):r<864e5?t("pa.audit_hours_ago",{count:Math.floor(r/36e5)}):t("pa.audit_days_ago",{count:Math.floor(r/864e5)})}var rl=({projectId:e,open:t,onOpenChange:r})=>{const{t:a}=at(),[s,n]=(0,fn.useState)([]),[i,o]=(0,fn.useState)(!1),[l,c]=(0,fn.useState)(null),[d,u]=(0,fn.useState)("all");return(0,fn.useEffect)(()=>{if(!t||!e)return;let r=!1;return o(!0),c(null),(async()=>{let t=Lt.from("pa_tool_audit_log").select("id, created_at, tool_name, status, args, result_summary, source, user_id").eq("project_id",e).order("created_at",{ascending:!1}).limit(200);"all"!==d&&(t=t.eq("status",d));const{data:a,error:s}=await t;r||(s?(c(s.message),n([])):n(a??[]),o(!1))})(),()=>{r=!0}},[t,e,d]),(0,jn.jsx)(xt,{open:t,onOpenChange:r,children:(0,jn.jsxs)(ht,{className:"max-w-2xl",children:[(0,jn.jsxs)(mt,{children:[(0,jn.jsxs)(ft,{className:"flex items-center gap-2",children:[(0,jn.jsx)(h,{className:"h-4 w-4"}),a("pa.audit_title")]}),(0,jn.jsx)(gt,{children:a("pa.audit_desc")})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)("span",{className:"text-xs text-muted-foreground",children:a("pa.audit_filter")}),(0,jn.jsxs)(aa,{value:d,onValueChange:u,children:[(0,jn.jsx)(ea,{className:"w-44 h-8 text-xs",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"all",children:a("pa.audit_all")}),(0,jn.jsx)(ra,{value:"success",children:a("pa.audit_success_only")}),(0,jn.jsx)(ra,{value:"error",children:a("pa.audit_errors_only")}),(0,jn.jsx)(ra,{value:"requires_confirmation",children:a("pa.audit_awaiting_confirmation")}),(0,jn.jsx)(ra,{value:"forbidden",children:a("pa.audit_forbidden")})]})]})]}),(0,jn.jsx)(_t,{className:"h-[60vh] pr-2",children:i?(0,jn.jsx)("p",{className:"text-sm text-muted-foreground py-8 text-center",children:a("common.loading")}):l?(0,jn.jsx)("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-3 text-xs text-destructive",children:a("pa.audit_read_failed",{error:l})}):0===s.length?(0,jn.jsx)("p",{className:"text-sm text-muted-foreground py-8 text-center",children:a("pa.audit_empty")}):(0,jn.jsx)("ul",{className:"space-y-2",children:s.map(e=>{const t=el[e.status]??{labelKey:"",icon:h,cls:"text-muted-foreground"},r=t.icon,s=t.labelKey?a(t.labelKey):e.status,n=e.result_summary||{},i=n.title||n.deal_title||n.note_id||n.deal_id||null;return(0,jn.jsxs)("li",{className:"rounded-md border bg-card px-3 py-2 text-sm",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)(r,{className:He("h-4 w-4 shrink-0",t.cls)}),(0,jn.jsx)("code",{className:"font-mono text-xs",children:e.tool_name}),(0,jn.jsx)(Pr,{variant:"outline",className:"text-[10px] uppercase",children:s}),e.source?(0,jn.jsx)(Pr,{variant:"secondary",className:"text-[10px]",children:e.source}):null,(0,jn.jsx)("span",{className:"ml-auto text-[10px] text-muted-foreground",children:tl(e.created_at,a)})]}),i?(0,jn.jsx)("p",{className:"mt-1 text-xs text-muted-foreground truncate",children:i}):null,"error"===e.status&&n.error?(0,jn.jsx)("p",{className:"mt-1 text-xs text-red-600 dark:text-red-400",children:String(n.error)}):null]},e.id)})})})]})})};function al({pending:e,onConfirm:t,onClose:r}){const{t:a}=at();return(0,jn.jsx)(Ct,{open:!!e,onOpenChange:e=>{e||r()},children:(0,jn.jsxs)(wt,{children:[(0,jn.jsxs)(It,{children:[(0,jn.jsx)(yt,{children:e?.preview.title||a("chat.confirm_action")}),(0,jn.jsx)(vt,{children:a("chat.outward_confirm_desc")})]}),e?.preview.channel&&(0,jn.jsx)("p",{className:"text-xs font-medium text-muted-foreground -mt-1",children:e.preview.channel}),e?.preview.body&&(0,jn.jsx)("div",{className:"rounded-md border border-border bg-muted/40 p-2 text-sm text-foreground whitespace-pre-wrap max-h-48 overflow-y-auto",children:e.preview.body}),(0,jn.jsxs)(kt,{children:[(0,jn.jsx)(St,{onClick:r,children:a("action.cancel")}),(0,jn.jsx)(Nt,{onClick:t,children:a("action.send")})]})]})})}var sl=[{titleKey:"pa.cat_tasks",icon:De,examples:[{labelKey:"pa.ex_task_deck",prompt:"Create a task to finish the deck by Friday"},{labelKey:"pa.ex_overdue",prompt:"What's overdue right now?"},{labelKey:"pa.ex_subtasks",prompt:'Break "Launch landing page" into subtasks'},{labelKey:"pa.ex_log_time",prompt:"Log 2 hours on the API task"}]},{titleKey:"pa.cat_goals",icon:j,examples:[{labelKey:"pa.ex_create_okr",prompt:"Create an OKR for Q3 growth"},{labelKey:"pa.ex_okr_risk",prompt:"Which OKRs are at risk?"},{labelKey:"pa.ex_link_tasks",prompt:"Link my current tasks to the activation objective"}]},{titleKey:"pa.cat_notes",icon:c,examples:[{labelKey:"pa.ex_save_note",prompt:"Save a note from today's standup"},{labelKey:"pa.ex_log_decision",prompt:"Log the decision to use Postgres and why"},{labelKey:"pa.ex_pricing_decision",prompt:"What did we decide about pricing?"}]},{titleKey:"pa.cat_calendar",icon:Te,examples:[{labelKey:"pa.ex_schedule_sync",prompt:"Schedule a team sync tomorrow at 2pm"},{labelKey:"pa.ex_find_slot",prompt:"Find a 30-min slot with the team this week"},{labelKey:"pa.ex_remind_acme",prompt:"Remind me to follow up with Acme on Monday"}]},{titleKey:"pa.cat_crm",icon:te,examples:[{labelKey:"pa.ex_stale_deals",prompt:"Show me stale deals"},{labelKey:"pa.ex_move_deal",prompt:"Move the Acme deal to Negotiation"},{labelKey:"pa.ex_pipeline",prompt:"Summarize the pipeline"},{labelKey:"pa.ex_add_contact",prompt:"Add a contact for [email protected]"}]},{titleKey:"pa.cat_whiteboards",icon:Q,examples:[{labelKey:"pa.ex_flowchart",prompt:"Draw a flowchart of our onboarding"},{labelKey:"pa.ex_whiteboard_arch",prompt:"Create a whiteboard for the system architecture"}]},{titleKey:"pa.cat_briefings",icon:se,examples:[{labelKey:"pa.ex_today_brief",prompt:"Brief me for today"},{labelKey:"pa.ex_team_blocking",prompt:"What's blocking the team?"},{labelKey:"pa.ex_eod",prompt:"End of day review"},{labelKey:"pa.ex_deep_think",prompt:"Deep think: should we raise now?"}]},{titleKey:"pa.cat_chat_email",icon:v,examples:[{labelKey:"pa.ex_post_update",prompt:"Post a quick update to #general"},{labelKey:"pa.ex_investor_email",prompt:"Draft an email to investors about our launch"}]}];function nl({open:e,onOpenChange:t,assistantName:r="Assad",onPick:a,disabled:s=!1}){const{t:n}=at();return(0,jn.jsx)(xt,{open:e,onOpenChange:t,children:(0,jn.jsxs)(ht,{className:"sm:max-w-lg max-h-[80vh] flex flex-col",children:[(0,jn.jsxs)(mt,{children:[(0,jn.jsx)(ft,{children:n("pa.catalog_title",{name:r})}),(0,jn.jsx)(gt,{children:n("pa.catalog_desc",{name:r})})]}),(0,jn.jsx)("div",{className:"overflow-y-auto pr-1 -mr-1 space-y-4",children:sl.map(e=>(0,jn.jsxs)("div",{children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 mb-1.5",children:[(0,jn.jsx)(e.icon,{className:"h-4 w-4 text-primary"}),(0,jn.jsx)("h4",{className:"text-sm font-semibold text-foreground",children:n(e.titleKey)})]}),(0,jn.jsx)("div",{className:"flex flex-wrap gap-1.5",children:e.examples.map(e=>(0,jn.jsx)("button",{onClick:()=>a(e.prompt),disabled:s,className:"px-2.5 py-1 text-xs rounded-full border border-border bg-muted/40 text-foreground
2/80 hover:bg-muted hover:text-foreground transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:bg-muted/40",children:n(e.labelKey)},e.labelKey))})]},e.titleKey))})]})})}var il=[/\b(let'?s|we should|need to|action item|todo|to-do|please|can you|could you|make sure|don'?t forget)\b/i,/\b(deadline|due by|by (monday|tuesday|wednesday|thursday|friday|tomorrow|next week|end of))\b/i,/\b(assign|assigned to|take care of|handle|follow up|follow-up)\b/i],ol=[/\b(we decided|decision:|let'?s go with|agreed|final call|we'?re going with|confirmed)\b/i,/\b(approved|sign ?off|green ?light|settled on|chose|picked)\b/i],ll=[/\b(let'?s meet|schedule a (meeting|call)|set up a (meeting|call)|book a meeting)\b/i,/\b(meeting at|call at|sync at|standup at)\b/i,/\b(let'?s (hop on|jump on|get on) a call)\b/i,/\b(can we (meet|talk|chat|discuss) (at|on|this|tomorrow|next))\b/i];function cl({message:e,onCreateTask:t,onLogDecision:r,onScheduleMeeting:a}){const{t:s}=at(),[n,i]=(0,fn.useState)(!1),[o,l]=(0,fn.useState)([]);(0,fn.useEffect)(()=>{i(!1),e.length>15?l(function(e){const t=[],r=e.length>4e3?e.slice(0,4e3):e;return il.some(e=>e.test(r))&&t.push({type:"task",labelKey:"chat.create_task",icon:(0,jn.jsx)(ee,{className:"w-3.5 h-3.5"})}),ol.some(e=>e.test(r))&&t.push({type:"decision",labelKey:"chat.log_decision",icon:(0,jn.jsx)(ve,{className:"w-3.5 h-3.5"})}),ll.some(e=>e.test(r))&&t.push({type:"meeting",labelKey:"chat.schedule_meeting",icon:(0,jn.jsx)(O,{className:"w-3.5 h-3.5"})}),t}(e)):l([])},[e]);const c=o.filter(e=>"task"===e.type?!!t:"decision"===e.type?!!r:!!a);if(n||0===c.length)return null;return(0,jn.jsx)(Ar,{children:(0,jn.jsxs)(Er.div,{initial:{opacity:0,y:4,height:0},animate:{opacity:1,y:0,height:"auto"},exit:{opacity:0,y:-4,height:0},className:"flex items-center gap-2 px-3 py-1.5 bg-primary/5 border border-primary/10 rounded-lg text-xs",children:[(0,jn.jsx)(se,{className:"w-3 h-3 text-primary shrink-0"}),(0,jn.jsx)("span",{className:"text-muted-foreground shrink-0",children:s("chat.actionable_label")}),(0,jn.jsx)("div",{className:"flex items-center gap-1.5",children:c.map(n=>(0,jn.jsxs)(Ye,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs gap-1 text-primary hover:text-primary hover:bg-primary/10",onClick:()=>(s=>{"task"===s.type&&t?t(e):"decision"===s.type&&r?r(e):"meeting"===s.type&&a&&a(e),i(!0)})(n),children:[n.icon,s(n.labelKey)]},n.type))}),(0,jn.jsx)("button",{onClick:()=>i(!0),"aria-label":s("a11y.dismiss"),title:s("a11y.dismiss"),className:"ml-auto p-0.5 text-muted-foreground hover:text-foreground transition-colors",children:(0,jn.jsx)(J,{className:"w-3 h-3"})})]})})}var dl=null,ul=null;var ml=({text:e,voiceId:t,className:r})=>{const{t:a}=at(),[s,n]=(0,fn.useState)("idle"),i=(0,fn.useRef)(null),o=(0,fn.useRef)(null),l=(0,fn.useRef)(!1),c=(0,fn.useRef)(!0),d=()=>{o.current&&(URL.revokeObjectURL(o.current),o.current=null)},u=()=>{const e=i.current;e&&(e.pause(),e.src="",dl===e&&(dl=null,ul=null),i.current=null),d(),c.current&&n("idle")};(0,fn.useEffect)(()=>(c.current=!0,()=>{if(c.current=!1,i.current){try{i.current.pause()}catch{}try{i.current.src=""}catch{}dl===i.current&&(dl=null,ul=null),i.current=null}o.current&&(URL.revokeObjectURL(o.current),o.current=null)}),[]);const m="loading"===s?ce:"playing"===s?de:_e;return(0,jn.jsx)("button",{type:"button",onClick:async()=>{if("playing"===s)return void u();if(l.current)return;ul&&ul();const r=function(e){return(e||"").replace(/```[\s\S]*?```/g," ").replace(/`[^`]*`/g," ").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/[*_~]/g,"").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim().slice(0,1500)}(e);if(r){l.current=!0,n("loading");try{const e=await Zi(),a=await fetch("https://eovwyecuppwlxsicmrno.supabase.co/functions/v1/elevenlabs-tts",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e||"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImVvdnd5ZWN1cHB3bHhzaWNtcm5vIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQ4OTU2MzEsImV4cCI6MjA5MDQ3MTYzMX0.dFQPraCGmk38oJFH8AUUMEdXRR7a6qlnUGFJpv41f7c"}`},body:JSON.stringify({text:r,voiceId:t})}),s=a.headers.get("Content-Type")||"";if(!a.ok||!s.startsWith("audio/")){const e=await a.text().catch(()=>"");throw new Error(`TTS request failed (${a.status}): ${e.slice(0,200)}`)}const l=await a.blob();if(!c.current)return;d();const m=URL.createObjectURL(l);o.current=m;const p=new Audio(m);i.current=p,dl=p,ul=u,p.onended=()=>
2{i.current===p&&(i.current=null,dl===p&&(dl=null,ul=null),d(),c.current&&n("idle"))},p.onerror=()=>{i.current===p&&(i.current=null,dl===p&&(dl=null,ul=null)),d(),c.current&&n("idle")},await p.play(),c.current&&n("playing")}catch(m){Ge.error("[ListenButton] audio playback failed",m),u(),Ae.error(a("pa.listen_failed"))}finally{l.current=!1}}},disabled:"loading"===s,"aria-busy":"loading"===s,className:He("p-0.5 rounded hover:bg-muted-foreground/10 transition-colors text-muted-foreground/40 hover:text-muted-foreground disabled:cursor-wait","playing"===s&&"text-success",r),title:a("playing"===s?"pa.listen_stop":"pa.listen"),"aria-label":a("playing"===s?"pa.listen_stop_aria":"pa.listen_aria"),children:(0,jn.jsx)(m,{className:He("h-3 w-3","loading"===s&&"animate-spin")})})},pl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function hl(e){const t=e.replace(/^thread-/,"");return`ID: ${(pl.test(t)?t.slice(0,8):t).toUpperCase()}`}var fl=e=>hl(e);function gl({projectId:e,currentThreadId:t,onThreadChange:r,onNewThread:a}){const{t:s}=at(),{user:n}=$t(),i=da(),[o,l]=(0,fn.useState)([]),[c,d]=(0,fn.useState)(!1);(0,fn.useEffect)(()=>{if(!e||!n)return;let t=!1;return(async()=>{d(!0);const r=await async function(e,t){const{data:r,error:a}=await Lt.rpc("list_pa_threads",{p_project_id:e});if(!a&&Array.isArray(r))return r.filter(e=>"string"==typeof e.thread_id&&e.thread_id).map(e=>({id:e.thread_id,name:fl(e.thread_id),is_private:!!e.is_private,created_at:e.first_message_at,last_message_at:e.last_message_at,message_count:Number(e.message_count)||0}));Ge.warn("[ThreadSwitcher] list_pa_threads unavailable â grouping recent rows instead",a);const{data:s,error:n}=await Lt.from("personal_assistant_conversations").select("thread_id, is_private, created_at").eq("project_id",e).eq("user_id",t).not("thread_id","is",null).order("created_at",{ascending:!1}).limit(1e3);if(n)return Ge.error("[ThreadSwitcher] failed to load threads",n,{projectId:e}),null;const i=new Map;for(const o of s||[]){const e=o.thread_id;if(!e)continue;const t=i.get(e);t?(t.message_count=(t.message_count||0)+1,t.is_private=t.is_private||!!o.is_private,o.created_at<t.created_at&&(t.created_at=o.created_at)):i.set(e,{id:e,name:fl(e),is_private:!!o.is_private,created_at:o.created_at,last_message_at:o.created_at,message_count:1})}return Array.from(i.values()).sort((e,t)=>new Date(t.last_message_at).getTime()-new Date(e.last_message_at).getTime())}(e,n.id);t||(r&&l(r),d(!1))})(),()=>{t=!0}},[e,n]);const u=t?o.find(e=>e.id===t):null,m=u?u.name:t?hl(t):s("pa.main_thread");return(0,jn.jsxs)(_a,{children:[(0,jn.jsx)(fa,{asChild:!0,children:(0,jn.jsxs)(Ye,{variant:"ghost",size:"sm",className:"h-7 gap-1 px-2 text-xs font-medium text-muted-foreground hover:text-foreground",title:s("pa.switch_thread"),children:[(0,jn.jsxs)("span",{className:"flex items-center gap-1.5",children:[u?.is_private&&(0,jn.jsx)(be,{className:"h-3 w-3"}),m]}),(0,jn.jsx)(Fe,{className:"h-3 w-3 opacity-50"})]})}),(0,jn.jsxs)(ga,{align:"start",className:"w-48",children:[(0,jn.jsxs)(xa,{onSelect:()=>r(null),"aria-current":t?void 0:"true",className:He("cursor-pointer",!t&&"bg-primary/10 text-primary"),children:[(0,jn.jsx)("span",{className:"flex-1",children:s("pa.main_thread")}),!t&&(0,jn.jsx)("span",{className:"text-xs","aria-hidden":"true",children:"â"})]}),o.length>0&&(0,jn.jsx)(pa,{}),o.map(a=>{const o=t===a.id;return(0,jn.jsxs)("div",{className:"group flex items-center gap-1",children:[(0,jn.jsxs)(xa,{onSelect:()=>r(a.id),"aria-current":o?"true":void 0,className:He("flex-1 min-w-0 min-h-6 cursor-pointer gap-1.5 py-1 text-xs font-medium",o?"text-primary":"text-muted-foreground"),children:[a.is_private&&(0,jn.jsx)(be,{className:"h-3 w-3 shrink-0",role:"img","aria-label":s("pa.private_thread")}),(0,jn.jsx)("span",{className:"truncate",children:a.name}),a.message_count?(0,jn.jsxs)("span",{className:"text-[10px] opacity-50",children:["(",a.message_count,")"]}):null]}),(0,jn.jsx)(xa,{onSelect:()=>{(async a=>{if(!n||!e)return;if(!(await i({title:s("pa.archive_thread_title"),description:s("pa.archive_thread_desc"),confirmLabel:s("action.archive")})))return;const{error:o}=await Lt.from("personal_assistant_conversations").update({thread_id:null}).eq("project_id",e).eq("user_id",n.id).eq("thread_id",a);if(o)return Ge.error("[ThreadSwitcher] archive failed",o),void Ae.error(s("pa.archive_thread_failed"));t===a&&r(null),l(e=>e.filter(e=>e.id!==a)),window.dispatchEvent(new CustomEvent("pa:thread-archived",{detail:{threadId:a}})),Ae.success(s("pa.thread_archived"))})(a.id)},title:s("pa.archive_thread"),"aria-label":`${s("pa.archive_thread")}: ${a.name}`,className:"h-6 w-6 shrink-0 cursor-pointer justify-center p-0 text-destructive opacity-70 transition-opacity focus:bg-destructive/10 focus:text-destructive focus:opacity-100 sm:opacity-0 sm:group-hover:opacity-100 sm:focus:opacity-100",children:(0,jn.jsx)(f,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]},a.id)}),o.length>0&&(0,jn.jsx)(pa,{}),(0,jn.jsxs)(xa,{onSelect:a,className:"cursor-pointer text-primary hover:text-primary",children:[(0,jn.jsx)(Ee,{className:"h-3.5 w-3.5 mr-1.5"}),(0,jn.jsx)("span",{className:"text-xs font-medium",children:s("pa.new_thread")})]})]})]})}var xl={[jt.DASHBOARD]:[{label:"Top 3 Today",prompt:"What are my 3 most important priorities today?",isSpecialType:void 0},{label:"Standup",prompt:"",isSpecialType:"standup"},{label:"Brief me",prompt:"",isSpecialType:"briefing"}],[jt.IDEATION]:[{label:"Refine concept",prompt:"Help me refine this idea into a sharp pitch: clarify the problem, who it's for, and why now?"},{label:"Market opportunity",prompt:"What's the market opportunity for this idea? Help me estimate TAM/SAM/SOM."},{label:"Next step",prompt:"What should my next step be to validate this idea?"}],[jt.NOTES]:[{label:"Summarize",prompt:"Summarize all my notes into key insights and action items."},{label:"Find insights",prompt:"What patterns or themes do you see across my notes?"},{label:"Search notes",prompt:"Open search"}],[jt.CUSTOMER_DISCOVERY]:[{label:"Interview guide",prompt:"What are the best questions to ask potential customers?"},{label:"Analyze feedback",prompt:"What patterns do you see in customer feedback I've collected?"},{label:"Next moves",prompt:"What customer discovery steps should I prioritize?"}],[jt.MARKET_RESEARCH]:[{label:"Competitive analysis",prompt:"Analyze my competitors. Who are the top 3 and what are their strengths?"},{label:"Market size",prompt:"Help me estimate TAM, SAM, and SOM for my market."},{label:"Trends",prompt:"What market trends should I be aware of for my industry?"}],[jt.STRATEGY]:[{label:"SWOT analysis",prompt:"Create a SWOT analysis for my business right now."},{label:"Positioning",prompt:"How should I position against competitors in my market?"},{label:"Go-to-market",prompt:"What is the best go-to-market strategy for my product?"}],[jt.PRODUCT]:[{label:"MVP scope",prompt:"What should my MVP include? What can wait for v2?"},{label:"User flows",prompt:"Help me design the core user flows for my product."},{label:"Roadmap",prompt:"What should my product roadmap look like for the next 6 months?"}],[jt.MARKETING]:[{label:"Brand voice",prompt:"Help me define my brand voice, tone, and messaging."},{label:"Go-to-market",prompt:"What are my best customer acquisition channels?"},{label:"Campaign ideas",prompt:"Give me 3 creative marketing campaign ideas."}],[jt.FINANCIALS]:[{label:"Unit economics",prompt:"Help me calculate and optimize my unit economics."},{label:"Revenue model",prompt:"Is my revenue model realistic? How can I improve it?"},{label:"Funding needs",prompt:"How much should I raise and for what milestones?"}],[jt.LEGAL]:[{label:"Entity structure",prompt:"What legal entity structure should I use?"},{label:"IP protection",prompt:"How should I protect my intellectual property?"},{label:"Due diligence",prompt:"What legal items should I prepare for fundraising?"}],[jt.TEAM]:[{label:"First hires",prompt:"Who should I hire first and in what order?"},{label:"Org structure",prompt:"What should my organizational structure look like?"},{label:"Culture",prompt:"Help me define my company culture and core values."}],[jt.PITCH_DECK]:[{label:"Story arc",prompt:"Help me craft a compelling narrative for my pitch."},{label:"Problem/solution",prompt:"How should I frame the problem and solution on the deck?"},{label:"Financials",prompt:"What should I include on the financials slide?"}],[jt.FUNDRAISING]:[{label:"Pipeline check",prompt:"Check my investor pipeline and tell me who to follow up with."},{label:"Investor prep",prompt:"Help me prepare for my next investor meeting."},{label:"Valuation",prompt:"What valuation should I ask for in this round?"}],[jt.OKRS]:[{label:"OKR health",prompt:"Review my OKRs. Which are at risk? Suggest what to do."},{label:"Top 3 Today",prompt:"What are my top 3 most important tasks linked to OKRs today?"}
2,{label:"Next quarter",prompt:"What should my OKRs be for next quarter?"}],[jt.TASKS]:[{label:"What's blocking?",prompt:"What tasks are blocked or overdue? Help me unblock them."},{label:"Top 3 Today",prompt:"What are the 3 most important tasks I should focus on today?"},{label:"Standup",prompt:"",isSpecialType:"standup"}],[jt.COMMUNICATION]:[{label:"Standup",prompt:"Summarize recent team chat. What's everyone working on?"},{label:"Decisions",prompt:"What major decisions were made in recent discussions?"},{label:"Action items",prompt:"What action items came up that need follow-up?"}],[jt.WHITEBOARD]:[{label:"Clarify",prompt:"Help me understand and refine what's on this whiteboard."},{label:"Feedback",prompt:"What improvements would you suggest for this design?"},{label:"Spec it out",prompt:"Help me turn this design into a detailed spec."}],[jt.GROWTH]:[{label:"Growth ideas",prompt:"What are my best growth opportunities right now?"},{label:"Campaign ideas",prompt:"What campaigns should I run this month?"},{label:"Metrics",prompt:"What metrics should I be tracking for growth?"}],[jt.FINANCE_DASHBOARD]:[{label:"Burn rate",prompt:"What's my burn rate? How much runway do I have?"},{label:"Cash forecast",prompt:"When do I run out of cash? What do I need to do?"},{label:"Cost cuts",prompt:"Where can I optimize costs without hurting progress?"}],[jt.INVESTOR_PIPELINE]:[{label:"Next steps",prompt:"Who should I reach out to next in my investor pipeline?"},{label:"Pitch review",prompt:"Give me feedback on my elevator pitch."},{label:"Deal progress",prompt:"Which investors are closest to saying yes?"}],[jt.CRM]:[{label:"Forecast",prompt:"Run the CRM forecast for this quarter. Break down committed vs weighted value."},{label:"Stale deals",prompt:"Find and tell me about deals that need follow-up in the next few days."},{label:"YTD summary",prompt:"Give me a YTD summary: new deals, won deals, value, top contacts."}],[jt.MAIL]:[{label:"Draft reply",prompt:"Help me draft a professional reply to a recent email."},{label:"Summarize",prompt:"Summarize my most important emails for today."},{label:"Cold email",prompt:"Help me write a compelling cold email."}],[jt.RISK]:[{label:"Risk assessment",prompt:"What are my biggest risks right now and their impact?"},{label:"Mitigation",prompt:"What should I do to mitigate these risks?"},{label:"Early warnings",prompt:"What warning signs should I watch for?"}],[jt.COMPETITOR_WAR_ROOM]:[{label:"Landscape",prompt:"How does my product compare to key competitors?"},{label:"Positioning",prompt:"What's my unique angle against these competitors?"},{label:"Differentiation",prompt:"How should I differentiate based on this competitive analysis?"}],[jt.MEETINGS]:[{label:"Meeting prep",prompt:"",isSpecialType:"prepare_meeting"},{label:"Summary",prompt:"Summarize this meeting. What were the key decisions?"},{label:"Action items",prompt:"What are the action items from this meeting?"}],[jt.CALENDAR]:[{label:"Meeting prep",prompt:"",isSpecialType:"prepare_meeting"},{label:"This week",prompt:"What meetings do I have this week and what should I prepare?"},{label:"Focus time",prompt:"When should I block deep work/focus time this week?"}],[jt.MENTOR]:[{label:"Ask mentor",prompt:"I need advice on a decision. What should I do?"},{label:"Feedback",prompt:"Give me honest feedback on my progress this quarter."},{label:"Debug issue",prompt:"Help me think through this challenge."}],[jt.WEBSITE]:[{label:"Copy review",prompt:"Review my website copy. Is the messaging clear and compelling?"},{label:"SEO",prompt:"What SEO improvements would help my search rankings?"},{label:"UX",prompt:"What UX improvements would help conversion?"}],[jt.GAME]:[{label:"Tips",prompt:"Give me tips to progress faster in this game."},{label:"Strategy",prompt:"What's the best strategy for this game?"},{label:"Help",prompt:"I'm stuck. Can you help me?"}],[jt.MARKETING_STRATEGY]:[{label:"Strategy",prompt:"What marketing strategy should I use?"},{label:"Channels",prompt:"Which channels should I focus on?"},{label:"Budget",prompt:"How should I allocate my marketing budget?"}],[jt.BRANDING]:[{label:"Brand strategy",prompt:"Help me develop my brand strategy."},{label:"Logo feedback",prompt:"Give me feedback on my logo concepts."},{label:"Brand voice",prompt:"Help me define my brand voice and tone."}],[jt.MARKETING_HUB]:[{label:"Campaigns",prompt:"What marketing campaigns should I run?"},{label:"Content calendar",prompt:"Help me plan my content calendar."},{label:"Metrics",prompt:"What marketing metrics should I track?"}],[jt.DRIVE]:[{label:"Find a file",prompt:"Help me find a file in the project drive."},{label:"Organize",prompt:"How should I organize the project's files and folders?"}],[jt.HR]:[{label:"Team overview",prompt:"Give me an overview of the team â headcount, roles, and anything needing attention."},{label:"Time off",prompt:"Who is on leave soon, and are there pending time-off requests?"}],[jt.PRICING]:[{label:"Pricing review",prompt:"Review my current pricing â is it aligned with the value we deliver?"},{label:"Competitor pricing",prompt:"How does my pricing compare to competitors?"}],[jt.GITHUB]:[{label:"Repo status",prompt:"Summarize recent activity in the connected GitHub repository."},{label:"Open PRs",prompt:"What pull requests are open and what state are they in?"}]};function _l(){try{return window.self!==window.top}catch{return!0}}async function bl(e){try{const t=document.createElement("a");return t.href=e,t.target="_blank",t.rel="noopener noreferrer",document.body.appendChild(t),t.click(),document.body.removeChild(t),{opened:!0,copied:!1}}catch{}try{return await navigator.clipboard.writeText(e),{opened:!1,copied:!0}}catch{return{opened:!1,copied:!1}}}var jl=({projectId:e})=>{const{status:t,myLink:r,loading:a,generateLinkCode:s,unlinkMe:n}=yn(e),i=da(),{t:o}=at(),[l,c]=(0,fn.useState)(!1);if(a&&!t)return null;if(!t?.connected)return null;return(0,jn.jsx)(lt,{className:"border-border bg-muted/30",children:(0,jn.jsxs)(rt,{className:"p-3 flex items-center gap-3",children:[(0,jn.jsx)("div",{className:"p-2 bg-primary/10 rounded-lg shrink-0",children:(0,jn.jsx)(w,{className:"w-4 h-4 text-primary"})}),(0,jn.jsx)("div",{className:"flex-1 min-w-0",children:r?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 text-sm",children:[(0,jn.jsx)(N,{className:"w-3.5 h-3.5 text-emerald-500"}),(0,jn.jsx)("span",{children:r.telegram_username?o("chat.telegram_linked_as",{username:r.telegram_username}):o("chat.telegram_linked")})]}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:o("chat.telegram_message_bot",{bot:t.botUsername})})]}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("p",{className:"text-sm font-medium",children:o("chat.telegram_chat_assistant")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:o("chat.telegram_connect_desc",{bot:t.botUsername})})]})}),r?(0,jn.jsxs)(Ye,{size:"sm",variant:"outline",onClick:async()=>
2{if(await i({title:o("chat.telegram_unlink_title"),confirmLabel:o("chat.telegram_unlink")}))try{await n(),Ae.success(o("chat.telegram_unlinked"))}catch(e){Ae.error(e instanceof Error?e.message:o("chat.telegram_unlink_failed"))}},className:"h-8 shrink-0",children:[(0,jn.jsx)(Le,{className:"w-3.5 h-3.5 mr-1.5"}),o("chat.telegram_unlink")]}):(0,jn.jsxs)(Ye,{size:"sm",onClick:async()=>{c(!0);try{const e=await s();if(!e)return void Ae.error(o("chat.telegram_link_code_error"));const t=await bl(e.deepLink);t.copied?Ae.info(o("chat.telegram_link_copied")):t.opened?Ae.info(o("chat.telegram_complete_link")):Ae.error(o("chat.telegram_open_error"))}catch(e){Ae.error(e instanceof Error?e.message:o("chat.telegram_start_link_error"))}finally{c(!1)}},disabled:l,className:"h-8 shrink-0",children:[l?(0,jn.jsx)(ce,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}):(0,jn.jsx)(L,{className:"w-3.5 h-3.5 mr-1.5"}),o("chat.telegram_link")]})]})})};function vl(e){const{user:t}=$t(),[r,a]=(0,fn.useState)(null),[s,n]=(0,fn.useState)(!0),[i,o]=(0,fn.useState)(null),l=(0,fn.useCallback)(async()=>{if(e&&t){n(!0);try{const{data:t,error:r}=await Lt.from("telegram_group_links").select("id, telegram_chat_id, telegram_chat_type, telegram_chat_title, bound_at, is_active").eq("project_id",e).maybeSingle();if(r&&"PGRST116"!==r.code)throw r;a(t||null)}catch(r){o(r instanceof Error?r.message:String(r))}finally{n(!1)}}},[e,t]);return(0,fn.useEffect)(()=>
2{l()},[l]),(0,fn.useEffect)(()=>{if(!e||!t)return;let r=null;return r=Lt.channel(Jt(`telegram-group-${e}-${t.id}`)).on("postgres_changes",{event:"INSERT",schema:"public",table:"telegram_group_links",filter:`project_id=eq.${e}`},e=>{a(e.new)}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"telegram_group_links",filter:`project_id=eq.${e}`},e=>{a(e.new)}).on("postgres_changes",{event:"DELETE",schema:"public",table:"telegram_group_links",filter:`project_id=eq.${e}`},()=>a(null)).subscribe(),()=>{r&&Lt.removeChannel(r)}},[e,t]),{groupLink:r,loading:s,error:i,generateBindCode:(0,fn.useCallback)(async()=>{if(!e||!t)return null;const r=crypto.randomUUID().replace(/-/g,"").slice(0,16),a=new Date(Date.now()+9e5).toISOString();try{const[{error:s},{data:n}]=await Promise.all([Lt.from("telegram_group_bind_codes").insert({code:r,project_id:e,created_by:t.id,expires_at:a}),Lt.from("project_telegram_integrations").select("bot_username").eq("project_id",e).maybeSingle()]);if(s)throw new Error(s.message);return{code:r,botUsername:n?.bot_username||null}}catch(s){throw o(s instanceof Error?s.message:String(s)),s}},[e,t]),unbindGroup:(0,fn.useCallback)(async()=>{if(!e||!r)return;const{data:t,error:s}=await Lt.from("telegram_group_links").delete().eq("id",r.id).select("id");if(s)throw new Error(s.message);if(!t?.length)throw new Error("The group could not be unbound");a(null)},[e,r]),refresh:l}}var yl=({projectId:e})=>{const{status:t}=yn(e),{groupLink:r,loading:a,generateBindCode:s,unbindGroup:n}=vl(e),i=da(),{t:o}=at(),[l,c]=(0,fn.useState)(!1),[d,u]=(0,fn.useState)(null),[m,p]=(0,fn.useState)(null);if(a)return null;if(!t?.connected)return null;return(0,jn.jsx)(lt,{className:"border-border bg-muted/30",children:(0,jn.jsxs)(rt,{className:"p-3 flex items-start gap-3",children:[(0,jn.jsx)("div",{className:"p-2 bg-primary/10 rounded-lg shrink-0",children:(0,jn.jsx)(G,{className:"w-4 h-4 text-primary"})}),(0,jn.jsx)("div",{className:"flex-1 min-w-0",children:r?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 text-sm",children:[(0,jn.jsx)(N,{className:"w-3.5 h-3.5 text-emerald-500"}),(0,jn.jsxs)("span",{children:[o("chat.telegram_group_linked"),r.telegram_chat_title?`: "${r.telegram_chat_title}"`:""]})]}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:o("chat.telegram_group_linked_desc")})]}):d?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("p",{className:"text-sm font-medium",children:o("chat.telegram_paste_group")}),(0,jn.jsxs)("div",{className:"mt-1.5 flex items-center gap-1.5",children:[(0,jn.jsxs)("code",{className:"flex-1 px-2 py-1 rounded bg-background border text-xs font-mono",children:["/linkstartup ",d]}),(0,jn.jsx)(Ye,{size:"sm",variant:"outline",className:"h-7 shrink-0",onClick:()=>{return e=`/linkstartup ${d}`,t=o("chat.telegram_link_command"),navigator.clipboard.writeText(e),void Ae.info(o("chat.telegram_copied",{label:t}));var e,t},"aria-label":o("chat.telegram_copy_command"),title:o("chat.telegram_copy_command"),children:(0,jn.jsx)(ye,{className:"w-3 h-3"})})]}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-1.5",children:o("chat.telegram_group_steps",{bot:m||t.botUsername})})]}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("p",{className:"text-sm font-medium",children:o("chat.telegram_bind_group")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:o("chat.telegram_bind_group_desc")})]})}),r?(0,jn.jsxs)(Ye,{size:"sm",variant:"outline",onClick:async()=>{if(await i({title:o("chat.telegram_unbind_title"),description:o("chat.telegram_unbind_desc"),confirmLabel:o("chat.telegram_unbind"),destructive:!0}))try{await n(),Ae.success(o("chat.telegram_group_unbound"))}catch(e){Ae.error(e instanceof Error?e.message:o("chat.telegram_unbind_failed"))}},className:"h-8 shrink-0",children:[(0,jn.jsx)(Le,{className:"w-3.5 h-3.5 mr-1.5"}),o("chat.telegram_unbind")]}):(0,jn.jsxs)(Ye,{size:"sm",onClick:async()=>{c(!0);try{const e=await s();if(!e)return void Ae.error(o("chat.telegram_bind_code_error"));u(e.code),p(e.botUsername),Ae.success(o("chat.telegram_bind_code_ready"))}catch(e){Ae.error(e instanceof Error?e.message:o("chat.telegram_generate_code_failed"))}finally{c(!1)}},disabled:l,className:"h-8 shrink-0",children:[l?(0,jn.jsx)(ce,{className:"w-3.5 h-3.5 animate-spin mr-1.5"}):null,o(d?"chat.telegram_new_code":"chat.telegram_generate_code")]})]})})};function wl({open:e,action:t,onClose:r,onConfirm:a}){const[s,n]=(0,fn.useState)("this");return(0,jn.jsx)(xt,{open:e,onOpenChange:e=>!e&&r(),children:(0,jn.jsxs)(ht,{className:"max-w-sm",children:[(0,jn.jsxs)(mt,{children:[(0,jn.jsxs)(ft,{children:["edit"===t?"Edit":"Delete"," recurring event"]}),(0,jn.jsxs)(gt,{children:["How much of this series do you want to ","edit"===t?"edit":"remove","?"]})]}),(0,jn.jsxs)(_s,{value:s,onValueChange:e=>n(e),className:"space-y-3 py-2",children:[(0,jn.jsxs)("div",{className:"flex items-start gap-3",children:[(0,jn.jsx)(xs,{value:"this",id:"scope-this",className:"mt-0.5"}),(0,jn.jsxs)(na,{htmlFor:"scope-this",className:"flex-1 cursor-pointer",children:[(0,jn.jsx)("span",{className:"font-medium block",children:"This event only"}),(0,jn.jsx)("span",{className:"text-xs text-muted-foreground",children:"Other occurrences are unchanged."})]})]}),(0,jn.jsxs)("div",{className:"flex items-start gap-3",children:[(0,jn.jsx)(xs,{value:"this_and_following",id:"scope-following",className:"mt-0.5"}),(0,jn.jsxs)(na,{htmlFor:"scope-following",className:"flex-1 cursor-pointer",children:[(0,jn.jsx)("span",{className:"font-medium block",children:"This and following events"}),(0,jn.jsx)("span",{className:"text-xs text-muted-foreground",children:"Past occurrences are kept; future ones change."})]})]}),(0,jn.jsxs)("div",{className:"flex items-start gap-3",children:[(0,jn.jsx)(xs,{value:"all",id:"scope-all",className:"mt-0.5"}),(0,jn.jsxs)(na,{htmlFor:"scope-all",className:"flex-1 cursor-pointer",children:[(0,jn.jsx)("span",{className:"font-medium block",children:"All events in the series"}),(0,jn.jsx)("span",{className:"text-xs text-muted-foreground",children:"Includes past and future occurrences."})]})]})]}),(0,jn.jsxs)(pt,{className:"gap-2",children:[(0,jn.jsx)(Ye,{variant:"ghost",onClick:r,children:"Cancel"}),(0,jn.jsx)(Ye,{variant:"delete"===t?"destructive":"default",onClick:()=>{a(s),r()},children:"delete"===t?"Delete":"OK"})]})]})})}var Nl=["MO","TU","WE","TH","FR","SA","SU"],kl=["M","T","W","T","F","S","S"],Sl=["Monday","Tuesday","Wednesday","Thursday","Frid
2ay","Saturday","Sunday"];function Il(e){const t=Yn(e);return t?`${(r=t).getFullYear()}-${In(r.getMonth()+1)}-${In(r.getDate())}`:"";var r}function Cl(e){if(!e)return{freq:"NONE",interval:1,byday:[],endMode:"never",count:10,until:""};const t={};e.split(";").forEach(e=>{const[r,a]=e.split("=");r&&void 0!==a&&(t[r]=a)});const r=t.FREQ||"NONE",a=t.INTERVAL?parseInt(t.INTERVAL):1,s=t.BYDAY?t.BYDAY.split(","):[];let n,i="never",o=10,l="";return t.COUNT&&(i="count",o=parseInt(t.COUNT)||10),t.UNTIL&&(i="until",n=t.UNTIL,l=Il(n)),{freq:r,interval:a,byday:s,endMode:i,count:o,until:l,untilRaw:n}}function El(e,t){if(!e)return"Does not repeat";const r=Cl(e),a=r.interval>1?`every ${r.interval} `:"every ";let s="";if("DAILY"===r.freq)s=`${a}${r.interval>1?"days":"day"}`;else if("WEEKLY"===r.freq)if(s=`${a}${r.interval>1?"weeks":"week"}`,r.byday.length>0){s+=` on ${r.byday.map(e=>({MO:"Mon",TU:"Tue",WE:"Wed",TH:"Thu",FR:"Fri",SA:"Sat",SU:"Sun"}[e]||e)).join(", ")}`}else t&&(s+=` on ${y(t,"EEEE")}`);else"MONTHLY"===r.freq?(s=`${a}${r.interval>1?"months":"month"}`,t&&(s+=` on day ${t.getDate()}`)):"YEARLY"===r.freq&&(s=`${a}${r.interval>1?"years":"year"}`,t&&(s+=` on ${y(t,"MMM d")}`));return"count"===r.endMode&&(s+=`, ${r.count} times`),"until"===r.endMode&&r.until&&(s+=`, until ${r.until}`),`Repeats ${s}`}function Tl({value:e,onChange:t,anchorDate:r}){const a=(0,fn.useMemo)(()=>Cl(e),[e]),s=(e,r)=>{t(function(e){if("NONE"===e.freq)return"";const t=[`FREQ=${e.freq}`];if(e.interval>1&&t.push(`INTERVAL=${e.interval}`),"WEEKLY"===e.freq&&e.byday.length>0&&t.push(`BYDAY=${e.byday.join(",")}`),"count"===e.endMode&&t.push(`COUNT=${Math.max(1,e.count)}`),"until"===e.endMode&&e.until)if(e.untilRaw&&Il(e.untilRaw)===e.until)t.push(`UNTIL=${e.untilRaw}`);else{const r=e.until.replace(/-/g,"");t.push(`UNTIL=${r}T235959Z`)}return t.join(";")}({...a,[e]:r}))};return(0,jn.jsxs)("div",{className:"space-y-3",children:[(0,jn.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,jn.jsxs)("div",{children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Repeat"}),(0,jn.jsxs)(aa,{value:a.freq,onValueChange:e=>s("freq",e),children:[(0,jn.jsx)(ea,{className:"h-9 mt-1",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsxs)(ta,{children:[(0,jn.jsx)(ra,{value:"NONE",children:"Does not repeat"}),(0,jn.jsx)(ra,{value:"DAILY",children:"Daily"}),(0,jn.jsx)(ra,{value:"WEEKLY",children:"Weekly"}),(0,jn.jsx)(ra,{value:"MONTHLY",children:"Monthly"}),(0,jn.jsx)(ra,{value:"YEARLY",children:"Yearly"})]})]})]}),"NONE"!==a.freq&&(0,jn.jsxs)("div",{children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Every"}),(0,jn.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[(0,jn.jsx)(Et,{type:"number",min:1,max:365,value:a.interval,onChange:e=>s("interval",Math.max(1,Number(e.target.value)||1)),className:"h-9 w-16"}),(0,jn.jsx)("span",{className:"text-sm text-muted-foreground",children:"DAILY"===a.freq?"day(s)":"WEEKLY"===a.freq?"week(s)":"MONTHLY"===a.freq?"month(s)":"year(s)"})]})]})]}),"WEEKLY"===a.freq&&(0,jn.jsxs)("div",{children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"On these days"}),(0,jn.jsx)("div",{className:"flex gap-1 mt-1",children:Nl.map((e,t)=>(0,jn.jsx)("button",{type:"button",onClick:()=>(e=>{const t=a.byday.includes(e)?a.byday.filter(t=>t!==e):[...a.byday,e];s("byday",t)})(e),"aria-label":Sl[t],"aria-pressed":a.byday.includes(e),className:He("h-8 w-8 rounded-full text-xs font-medium transition-colors border",a.byday.includes(e)?"bg-primary text-primary-foreground border-primary":"bg-background text-foreground border-border hover:bg-accent"),children:kl[t]},e))})]}),"NONE"!==a.freq&&(0,jn.jsxs)("div",{children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Ends"}),(0,jn.jsxs)("div",{className:"grid grid-cols-3 gap-2 mt-1",children:[(0,jn.jsx)(Ye,{type:"button",size:"sm",variant:"never"===a.endMode?"default":"outline",onClick:()=>s("endMode","never"),children:"Never"}),(0,jn.jsx)(Ye,{type:"button",size:"sm",variant:"count"===a.endMode?"default":"outline",onClick:()=>s("endMode","count"),children:"Afterâ¦"}),(0,jn.jsx)(Ye,{type:"button",size:"sm",variant:"until"===a.endMode?"default":"outline",onClick:()=>s("endMode","until"),children:"On date"})]}),"count"===a.endMode&&(0,jn.jsxs)("div",{className:"flex items-center gap-2 mt-2",children:[(0,jn.jsx)(Et,{type:"number",min:1,max:999,value:a.count,onChange:e=>s("count",Math.max(1,Number(e.target.value)||1)),className:"h-9 w-20"}),(0,jn.jsx)("span",{className:"text-sm text-muted-foreground",children:"occurrences"})]}),"until"===a.endMode&&(0,jn.jsx)(Et,{type:"date",value:a.until,onCh
2ange:e=>s("until",e.target.value),className:"h-9 mt-2"})]}),"NONE"!==a.freq&&(0,jn.jsx)("p",{className:"text-xs text-muted-foreground italic",children:El(e,r)})]})}var Al="onetab_calendar_prefs",Dl={weekStartsOn:1,dayStartHour:7,dayEndHour:22,slotMinutes:30,defaultReminderMinutes:10,showDeclined:!0,timeZone:""};function Ol(){try{const e=localStorage.getItem(Al);return e?{...Dl,...JSON.parse(e)}:Dl}catch{return Dl}}function Rl(){const[e,t]=(0,fn.useState)(()=>Ol());return(0,fn.useEffect)(()=>{const e=()=>t(Ol());return window.addEventListener("calendar-prefs-updated",e),()=>window.removeEventListener("calendar-prefs-updated",e)},[]),{prefs:e,update:(0,fn.useCallback)(e=>{t(t=>{const r={...t,...e};try{localStorage.setItem(Al,JSON.stringify(r)),window.dispatchEvent(new Event("calendar-prefs-updated"))}catch(a){Ge.error("Failed to persist calendar prefs:",a)}return r})},[]),reset:(0,fn.useCallback)(()=>{try{localStorage.removeItem(Al)}catch{}t(Dl),window.dispatchEvent(new Event("calendar-prefs-updated"))},[])}}function Ml(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone||""}catch{return""}}function Pl(e){const t=Ht(jt.MEETINGS),{isModuleAllowed:r,loading:a}=fr(e??null);return!!e&&(!t.loading&&!a&&(!1!==t.active&&r(jt.MEETINGS)))}var Ll=new Set(["error","cancelled"]);function Ul(e){try{const t=new URL(e.trim());t.hostname.includes("meetingservice-production")&&t.hostname.includes("railway.app")&&(t.hostname="www.onepizza.io",t.port=""),"onepizza.io"===t.hostname&&(t.hostname="www.onepizza.io"),t.hostname.includes("meetingbot-production")&&t.hostname.includes("railway.app")&&(t.hostname="www.justheretolisten.io",t.port="");for(const e of["name","displayName","user","email"])t.searchParams.delete(e);return t.toString()}catch{return e.trim()}}var $l=["blue","red","green","purple","orange","teal"],Fl=[{value:"-1",label:"No reminder"},{value:"0",label:"At start time"},{value:"5",label:"5 minutes before"},{value:"10",label:"10 minutes before"},{value:"15",label:"15 minutes before"},{value:"30",label:"30 minutes before"},{value:"60",label:"1 hour before"},{value:"120",label:"2 hours before"},{value:"1440",label:"1 day before"},{value:"10080",label:"1 week before"}],Wl=/meet\.google\.com|zoom\.us|teams\.microsoft\.com|whereby\.com|webex\.com|jit\.si|meetingservice-production\.up\.railway\.app|onepizza\.io/i;function Kl(e){return`${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`}function Hl(e){if(e.isAllDay){const t=zn(e.startDate,e.endDate||e.startDate);return{start:new Date(t.start_time),end:new Date(t.end_time)}}const[t,r]=e.startTime.split(":").map(Number),[a,s]=e.endTime.split(":").map(Number);return{start:Z(ge(Ne(e.startDate),t||0),r||0),end:Z(ge(Ne(e.endDate||e.startDate),a||0),s||0)}}function ql(e){if(e.isAllDay)return Ne(e.endDate||e.startDate)<Ne(e.startDate)?"The end date is before the start date.":null;const{start:t,end:r}=Hl(e);return r<=t?"The event must end after it starts.":null}function zl({value:e,onChange:t,className:r}){const[a,s]=(0,fn.useState)(!1),[n,i]=(e||"00:00").split(":"),o=parseInt(n,10)||0,l=parseInt(i,10)||0,c=Array.from({length:24},(e,t)=>t),d=(e,r)=>{t(`${String(e).padStart(2,"0")}:${String(r).padStart(2,"0")}`)};return(0,jn.jsxs)(ca,{open:a,onOpenChange:s,children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsxs)(Ye,{type:"button",variant:"outline",size:"sm",className:He("w-full justify-start text-left text-sm font-normal h-9 px-2 gap-1",r),children:[(0,jn.jsx)(Ue,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,jn.jsx)("span",{className:"truncate",children:e||"--:--"})]})}),(0,jn.jsx)(la,{className:"w-[160px] p-0",align:"start",sideOffset:4,children:(0,jn.jsxs)("div",{className:"flex h-56",children:[(0,jn.jsxs)("div",{className:"w-20 overflow-y-auto border-r border-border",children:[(0,jn.jsx)("div",{className:"px-2 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground bg-muted/50 sticky top-0 text-center",children:"Hour"}),c.map(e=>(0,jn.jsx)("button",{type:"button",onClick:()=>d(e,l),className:He("w-full px-2 py-1.5 text-sm text-center hover:bg-accent transition-colors",e===o&&"bg-primary/10 text-primary font-medium"),children:String(e).padStart(2,"0")},e))]}),(0,jn.jsxs)("div",{className:"w-20 overflow-y-auto",children:[(0,jn.jsx)("div",{className:"px-2 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground bg-muted/50 sticky top-0 text-center",children:"Min"}),[0,5,10,15,20,25,30,35,40,45,50,55].map(e=>(0,jn.jsx)("button",{type:"button",onClick:()=>d(o,e),className:He("w-full px-2 py-1.5 text-sm text-center hover:bg-accent transition-colors",e===l&&"bg-primary/10 text-primary font-medium"),children:String(e).padStart(2,"0")},e))]})]})})]})}function Vl({open:e,onClose:t,onSave:r,onUpdate:a,onDelete:s,event:n,duplicateSource:i,defaultDate:o,defaultHour:l,defaultTitle:c,template:d,projectId:u}){const p=da(),{t:h,tn:_}=at(),{prefs:b}=Rl(),j=Pl(u),v=!!n,w=n||i,N=Fl.some(e=>e.value===String(b.defaultReminderMinutes))?String(b.defaultReminderMinutes):"10",k=(0,fn.useCallback)(()=>
2{if(w){let e=new Date(w.start_time),t=new Date(w.end_time);if(w.is_all_day){const r=qn(w);e=Z(ge(r.first,9),0),t=Z(ge(r.last,10),0)}const r=w.location||"",a=Wl.test(r),s=/onepizza\.io|meetingservice-production/i.test(r),n=a&&!s?"other":"onetap";return{title:w.title+(i?" (copy)":""),description:w.description||"",location:r,startDate:e,startTime:Kl(e),endDate:t,endTime:Kl(t),isAllDay:!!w.is_all_day,color:w.color||"blue",recurrence:w.recurrence_rule||"",reminder:null!==w.reminder_minutes&&void 0!==w.reminder_minutes?String(w.reminder_minutes):"-1",attendeeInput:"",attendees:(w.attendees||[]).map(e=>e.email||e),sendBot:!1,botName:"1tab.ai Notetaker",isMeeting:a,meetingProvider:n}}const e=new Date,t=o||e,r=void 0!==l?Z(ge(t,l),0):Z(ge(t,e.getHours()),e.getMinutes());if(d){const e=Math.max(5,Math.min(1440,d.duration_minutes||60)),t=m(r,e),a=d.default_location||"",s=$l.includes(d.color||"")?d.color:"blue",n=null===d.default_reminder_minutes||void 0===d.default_reminder_minutes?N:d.default_reminder_minutes<0?"-1":String(d.default_reminder_minutes);return{title:d.title||d.name||c||"",description:d.description||"",location:a,startDate:r,startTime:Kl(r),endDate:t,endTime:Kl(t),isAllDay:!1,color:s,recurrence:d.default_recurrence_rule||"",reminder:n,attendeeInput:"",attendees:(d.default_attendees||[]).map(e=>("string"==typeof e?e:e?.email||"").trim().toLowerCase()).filter(e=>e.includes("@")),sendBot:!1,botName:"1tab.ai Notetaker",isMeeting:!!d.is_meeting||Wl.test(a),meetingProvider:Wl.test(a)&&!/onepizza\.io|meetingservice-production/i.test(a)?"other":"onetap"}}const a=H(r,1);return{title:c??"",description:"",location:"",startDate:r,startTime:Kl(r),endDate:a,endTime:Kl(a),isAllDay:!1,color:"blue",recurrence:"",reminder:N,attendeeInput:"",attendees:[],sendBot:!1,botName:"1tab.ai Notetaker",isMeeting:!1,meetingProvider:"onetap"}},[n,i,o,l,c,d,N]),[S,I]=(0,fn.useState)(k),[C,E]=(0,fn.useState)(!1),[T,A]=(0,fn.useState)(!1),[D,O]=(0,fn.useState)(null),[R,M]=(0,fn.useState)(!1),[P,U]=(0,fn.useState)([]),[$,F]=(0,fn.useState)([]),[W,V]=(0,fn.useState)({}),[B,Y]=(0,fn.useState)([]),{user:X}=$t(),ee=(0,fn.useRef)(null),[te,re]=(0,fn.useState)(null),ae=(0,fn.useRef)(null),se=(0,fn.useRef)(null),ne=(0,fn.useRef)(null),ie=Wl.test(S.location);(0,fn.useEffect)(()=>{e&&I(k())},[e,k]);const[oe,ce]=(0,fn.useState)([]),[de,ue]=(0,fn.useState)(null),me=(0,fn.useRef)(null),pe=(0,fn.useRef)(!1);(0,fn.useEffect)(()=>{if(ce([]),ue(null),me.current=null,pe.current=!1,!e||!n?.id||!j)return;let t=!1;const r=Fi(n.id),a=(async()=>{const{data:e,error:t}=await Lt.from("meeting_recordings").select("id, status, meeting_url, scheduled_at, created_at").eq("calendar_event_id",r).order("created_at",{ascending:!1}).limit(50);return t?(Ge.warn("Failed to load the notetaker state for this event",t),[]):e||[]})(),s=Promise.all([a,u?vi(r,u):Promise.resolve(null)]).then(([e,t])=>({recordings:e,setting:t}));return me.current=s,s.then(({recordings:e,setting:r})=>{if(t)return;ce(e),ue(r);const a=!!n.location&&!!function(e,t,r){const a=Date.parse(r);if(!Number.isFinite(a))return null;const s=Ul(t);for(const n of e){if(Ll.has(n.status))continue;if(Ul(n.meeting_url)!==s)continue;if(n.scheduled_at){const e=Date.parse(n.scheduled_at);if(Number.isFinite(e)&&Math.abs(e-a)<=6e4)return n;continue}const e=Date.parse(n.created_at);if(Number.isFinite(e)&&Math.abs(e-a)<=216e5)return n}return null}(e,n.location,n.start_time);pe.current||!r?.enabled&&!a||I(e=>({...e,sendBot:!0,botName:r?.botName||e.botName}))}),()=>{t=!0}},[e,n?.id,n?.location,n?.start_time,j,u]),(0,fn.useEffect)(()=>{if(!e)return;(async()=>{const{data:{user:e}}=await Lt.auth.getUser();if(!e)return;const[,{data:t}]=await Promise.all([(async()=>{if(!u)return;const{data:e}=await Lt.from("project_members").select("user_id").eq("project_id",u).not("user_id","is",null);if(e?.length){const t=e.map(e=>e.user_id).filter(Boolean),{data:r}=await Lt.from("profiles").select("user_id, display_name, email, avatar_url").in("user_id",t);r&&U(r.filter(e=>e.email).map(e=>({email:e.email,name:e.display_name||e.email||"Unknown",avatarUrl:e.avatar_url||ws(e.user_id),type:"team"})))}})(),Lt.from("user_calendar_events_manual").select("attendees").eq("user_id",e.id).not("attendees","is",null).order("start_time",{ascending:!1}).limit(50)]);if(t?.length){const e=new Set;for(const r of t){const t=r.attendees;if(Array.isArray(t))for(const r of t){const t="string"==typeof r?r:r?.email;t&&t.includes("@")&&e.add(t.toLowerCase())}}F(Array.from(e).map(e=>({email:e,name:e,type:"recent"})))}})()},[e,u]),(0,fn.useEffect)(()=>
2{if(e&&u&&0!==S.attendees.length)return ne.current&&clearTimeout(ne.current),ne.current=setTimeout(async()=>{try{const e=P.map(e=>e.email.toLowerCase()),t=S.attendees.filter(t=>e.includes(t.toLowerCase()));if(0===t.length)return void V({});const{data:r}=await Lt.from("profiles").select("user_id, email").in("email",t);if(!r?.length)return;if(0===r.map(e=>e.user_id).filter(Boolean).length)return;const{start:a,end:s}=Hl(S);if(s<=a)return void V({});const{data:n,error:i}=await Lt.rpc("check_team_availability",{p_project_id:u,p_check_start:a.toISOString(),p_check_end:s.toISOString()});if(!i&&n){const e=new Map;r.forEach(t=>{t.email&&e.set(t.user_id,t.email.toLowerCase())});const t={};for(const r of n){const a=e.get(r.user_id);a&&(t[a]=r.is_busy)}V(t)}}catch(e){Ge.error("Failed to check availability:",e)}},600),()=>{ne.current&&clearTimeout(ne.current)};V({})},[e,u,S.attendees,S.startTime,S.endTime,S.startDate,S.endDate,S.isAllDay,P]),(0,fn.useEffect)(()=>{if(e&&X&&!S.isAllDay)return ee.current&&clearTimeout(ee.current),ee.current=setTimeout(async()=>{const{start:e,end:t}=Hl(S);if(t<=e)return void Y([]);const r=await async function(e,t,r,a){const s=new Date(t),n=new Date(r);if(!(n>s))return[];const i=a?a.replace(/_r\d+$/,""):null,o=()=>Lt.from("user_calendar_events_manual"),[l,c]=await Promise.all([o().select("*").eq("user_id",e).is("recurrence_rule",null).lt("start_time",r).gt("end_time",t).limit(200),o().select("*").eq("user_id",e).not("recurrence_rule","is",null).lt("start_time",z(n,1).toISOString()).limit(500)]);if(l.error||c.error)return Ge.error("Conflict check failed:",l.error||c.error),[];const d=[];for(const u of[...l.data||[],...c.data||[]])if(u.id!==i&&!u.is_all_day&&"declined"!==u.rsvp_status)for(const e of si(u,s,n))e.start<n&&e.end>s&&d.push({id:u.id,title:u.title,start_time:e.start.toISOString(),end_time:e.end.toISOString()});return d.sort((e,t)=>e.start_time.localeCompare(t.start_time)),d.slice(0,20)}(X.id,e.toISOString(),t.toISOString(),n?.id);Y(r)},400),()=>{ee.current&&clearTimeout(ee.current)};Y([])},[e,X,S.startDate,S.endDate,S.startTime,S.endTime,S.isAllDay,n?.id]),(0,fn.useEffect)(()=>{const e=e=>{ae.current&&!ae.current.contains(e.target)&&se.current&&!se.current.contains(e.target)&&M(!1)};return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);const he=e=>y(new Date(e),"EEE, MMM d, p"),fe=async(e,t,r)=>{if(!u)return;const a=await ji({calendarEventId:e,projectId:u,enabled:t,botName:S.botName||void 0,fallbackTimeZone:An()||void 0,includeInProgress:r.includeInProgress});if(!1===a.ok)return void Ae.error(h("cal.saved_notetaker_update_failed",{reason:a.error}),{duration:1e4});const s=Ni(a.result,{nowMs:Date.now(),formatDate:he});!s||r.quiet&&"warning"!==s.tone||("success"===s.tone?Ae.success(s.message,{duration:8e3}):"warning"===s.tone?Ae.warning(s.message,{duration:1e4}):Ae.info(s.message,{duration:8e3}))},xe=async()=>{if(!j||!u)return{sync:!1,enabled:void 0,hadNotetaker:!1};const e=me.current?await me.current:null,t=e?.recordings??oe,r=!!(e?e.setting:de)?.enabled||t.some(e=>"scheduling"===e.status||"joining"===e.status),a=Wl.test(S.location)||S.isMeeting&&"onetap"===S.meetingProvider;return a&&S.sendBot?{sync:!0,enabled:!0,hadNotetaker:r}:a&&pe.current?{sync:!0,enabled:!1,hadNotetaker:r}:{sync:r,enabled:void 0,hadNotetaker:r}},_e=e=>{const t=(e||S.attendeeInput).trim().toLowerCase();t&&t.includes("@")&&(S.attendees.includes(t)?(O(t),setTimeout(()=>O(null),3e3)):(I(e=>({...e,attendees:[...e.attendees,t],attendeeInput:""})),O(null))),e||I(e=>({...e,attendeeInput:""}))},be=S.attendeeInput.toLowerCase(),je=P.filter(e=>!S.attendees.includes(e.email.toLowerCase())&&(e.name.toLowerCase().includes(be)||e.email.toLowerCase().includes(be))),ve=$.filter(e=>!S.attendees.includes(e.email.toLowerCase())&&!P.some(t=>t.email.toLowerCase()===e.email.toLowerCase())&&e.email.toLowerCase().includes(be)),ke=je.length>0||ve.length>0,Se=(ie||S.isMeeting&&"onetap"===S.meetingProvider)&&u&&j,Ie=oe.filter(e=>"scheduling"===e.status&&!!e.scheduled_at&&Date.parse(e.scheduled_at)>Date.now()).sort((e,t)=>
2Date.parse(e.scheduled_at)-Date.parse(t.scheduled_at)),Ce=ql(S),Ee=e=>I(t=>{const r=g(Ne(e),Ne(t.startDate));return{...t,startDate:e,endDate:z(t.endDate||t.startDate,r)}});return(0,jn.jsxs)(xt,{open:e,onOpenChange:e=>!e&&t(),children:[(0,jn.jsxs)(ht,{className:"max-w-2xl max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[(0,jn.jsx)(mt,{children:(0,jn.jsxs)("div",{className:"flex items-center gap-3",children:[(0,jn.jsx)("div",{className:He("w-1 self-stretch rounded-full shrink-0 min-h-[1.5rem]",Pi[S.color].dot)}),(0,jn.jsx)(ft,{className:"text-base font-semibold leading-snug",children:v?"Edit Event":i?"Duplicate Event":"New Event"})]})}),(0,jn.jsxs)("div",{className:"space-y-4",children:[(0,jn.jsxs)("div",{children:[(0,jn.jsx)(na,{htmlFor:"event-title",className:"text-xs text-muted-foreground",children:"Title"}),(0,jn.jsx)(Et,{id:"event-title",value:S.title,onChange:e=>I(t=>({...t,title:e.target.value})),placeholder:"Event title",autoFocus:!0,className:"mt-1 text-base font-medium h-10"})]}),(0,jn.jsxs)("div",{className:"relative",children:[(0,jn.jsxs)("div",{className:"flex items-center justify-between",children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,jn.jsx)(G,{className:"h-3.5 w-3.5"}),"Attendees"]}),v&&n&&S.attendees.length>0&&(0,jn.jsx)(Ye,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs gap-1",onClick:async()=>{if(n)try{const e=await async function(){const{data:{session:e}}=await Lt.auth.getSession();if(!e?.access_token)throw new Error("Not authenticated â please sign in");return{Authorization:`Bearer ${e.access_token}`,"Content-Type":"application/json"}}(),t=ua("send-calendar-invite");if(!t)return void Ae.error(h("cal.invites_not_configured"));const r=Fi(n.id),a=await fetch(t,{method:"POST",headers:e,body:JSON.stringify({eventId:r,inviteEmails:S.attendees,organizerName:""})});if(a.ok){const e=await a.json().catch(()=>({})),t=(e.results||[]).filter(e=>!e.ok).length,r=(e.results||[]).length-t;0===t?Ae.success(_("cal.invites_sent",r)):Ae.warning(h("cal.invites_partial",{sent:r,failed:t}))}else{const e=await a.json().catch(()=>({}));Ae.error(e?.error||h("cal.invites_send_failed"))}}catch(e){Ge.error("send-calendar-invite failed",e),Ae.error(h("cal.invites_send_failed"))}},children:"Send invites"})]}),S.attendees.length>0&&(0,jn.jsx)("div",{className:"flex flex-wrap gap-1 mt-1 mb-1.5",children:S.attendees.map(e=>(0,jn.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs bg-muted px-2 py-0.5 rounded-full",children:[void 0!==W[e.toLowerCase()]&&(0,jn.jsx)("span",{className:He("w-2 h-2 rounded-full shrink-0",W[e.toLowerCase()]?"bg-destructive":"bg-primary"),title:W[e.toLowerCase()]?"Busy at this time":"Available","aria-hidden":!0}),e,void 0!==W[e.toLowerCase()]&&(0,jn.jsx)("span",{className:"text-[10px] text-muted-foreground",children:W[e.toLowerCase()]?"· busy":"· free"}),(0,jn.jsx)("button",{type:"button",onClick:()=>I(t=>({...t,attendees:t.attendees.filter(t=>t!==e)})),"aria-label":`Remove ${e}`,children:(0,jn.jsx)(J,{className:"h-3 w-3"})})]},e))}),(0,jn.jsxs)("div",{className:"flex gap-2",children:[(0,jn.jsx)(Et,{ref:se,value:S.attendeeInput,onChange:e=>I(t=>({...t,attendeeInput:e.target.value})),placeholder:"[email protected]",onFocus:()=>M(!0),onKeyDown:e=>{"Enter"===e.key&&(e.preventDefault(),_e()),"Escape"===e.key&&M(!1)}}),(0,jn.jsx)(Ye,{type:"button",variant:"outline",size:"sm",onClick:()=>{S.attendeeInput.trim()&&_e(),M(!0),se.current?.focus()},children:"Add"})]}),D&&(0,jn.jsxs)("p",{className:"text-xs text-amber-500 mt-1",children:[D," is already in the list"]}),R&&ke&&(0,jn.jsxs)("div",{ref:ae,className:"absolute left-0 right-0 top-full mt-1 z-50 bg-popover border border-border rounded-lg shadow-lg overflow-hidden max-h-48 overflow-y-auto",children:[je.length>0&&(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("div",{className:"px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground bg-muted/50",children:"Team"}),je.map(e=>(0,jn.jsxs)("button",{type:"button",onClick:()=>{_e(e.email),M(!0)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-sm text-left hover:bg-accent transition-colors",children:[(0,jn.jsxs)(ys,{className:"w-6 h-6",children:[(0,jn.jsx)(vs,{src:e.avatarUrl}),(0,jn.jsx)(js,{className:"text-[10px]",children:e.name.charAt(0).toUpperCase()})]}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("span",{className:"font-medium truncate block",children:e.name}),e.name!==e.email&&(0,jn.jsx)("span",{className:"text-xs text-muted-foreground truncate block",children:e.email})]})]},e.email))]}),ve.length>0&&(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("div",{className:"px-3 py-1.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground bg-muted/50",children:"Recent"}),ve.map(e=>(0,jn.jsxs)("button",{type:"button",onClick:()=>{_e(e.email),M(!0)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-sm text-left hover:bg-accent transition-colors",children:[(0,jn.jsx)(ys,{className:"w-6 h-6",children:(0,jn.jsx)(js,{className:"text-[10px]",children:e.email.charAt(0).toUpperCase()})}),(0,jn.jsx)("span",{className:"truncate",children:e.email})]},e.email))]})]})]}),(0,jn.jsxs)("div",{className:"rounded-lg border border-border bg-muted/30 p-3 space-y-3",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)(we,{className:"h-4 w-4 text-primary"}),(0,jn.jsx)(na,{className:"flex-1 text-sm font-medium",children:"This is a meeting"}),(0,jn.jsx)(sa,{checked:S.isMeeting,onCheckedChange:e=>I(t=>({...t,isMeeting:e})),"aria-label":"This is a meeting"})]}),S.isMeeting&&(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Meeting provider"}),(0,jn.jsxs)("div",{className:"flex gap-2",children:[(0,jn.jsx)("button",{type:"button",onClick:()=>I(e=>({...e,meetingProvider:"onetap"})),className:He("flex-1 rounded-md border px-3 py-2 text-sm font-medium transition-colors","oneta
2p"===S.meetingProvider?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:"Meeting"}),(0,jn.jsx)("button",{type:"button",onClick:()=>I(e=>({...e,meetingProvider:"other"})),className:He("flex-1 rounded-md border px-3 py-2 text-sm font-medium transition-colors","other"===S.meetingProvider?"border-primary bg-primary/10 text-primary":"border-border bg-background text-muted-foreground hover:bg-muted"),children:"Other meeting service"})]}),"onetap"===S.meetingProvider&&(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:"A meeting link will be auto-generated when you save."}),"other"===S.meetingProvider&&(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:"Paste your Google Meet, Zoom, or Teams link below. You can still enable AI recording."})]})]}),(0,jn.jsxs)("div",{className:"rounded-lg border border-border bg-muted/20 p-3 space-y-3",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)(Ue,{className:"h-4 w-4 text-muted-foreground"}),(0,jn.jsx)(na,{className:"flex-1 text-sm font-medium",children:"When"}),(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)(sa,{id:"all-day",checked:S.isAllDay,onCheckedChange:e=>I(t=>({...t,isAllDay:e}))}),(0,jn.jsx)(na,{htmlFor:"all-day",className:"text-xs text-muted-foreground cursor-pointer",children:"All day"})]})]}),S.isAllDay?(0,jn.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Start date"}),(0,jn.jsxs)(ca,{children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",className:"w-full justify-start text-left text-sm font-normal h-9 px-2 gap-1",children:[(0,jn.jsx)(K,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,jn.jsx)("span",{className:"truncate",children:y(S.startDate,"d MMM yy")})]})}),(0,jn.jsx)(la,{className:"w-auto p-0",align:"start",children:(0,jn.jsx)(Ts,{mode:"single",selected:S.startDate,onSelect:e=>e&&Ee(e),className:"p-3 pointer-events-auto"})})]})]}),(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"End date"}),(0,jn.jsxs)(ca,{children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",className:"w-full justify-start text-left text-sm font-normal h-9 px-2 gap-1",children:[(0,jn.jsx)(K,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,jn.jsx)("span",{className:"truncate",children:y(S.endDate,"d MMM yy")})]})}),(0,jn.jsx)(la,{className:"w-auto p-0",align:"start",children:(0,jn.jsx)(Ts,{mode:"single",selected:S.endDate,onSelect:e=>e&&I(t=>({...t,endDate:e})),className:"p-3 pointer-events-auto"})})]})]})]}):(0,jn.jsxs)("div",{className:"grid grid-cols-2 gap-2",children:[(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Start date"}),(0,jn.jsxs)(ca,{children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",className:"w-full justify-start text-left text-sm font-normal h-9 px-2 gap-1","aria-label":`Start date, ${y(S.startDate,"d MMMM yyyy")}`,children:[(0,jn.jsx)(K,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,jn.jsx)("span",{className:"truncate",children:y(S.startDate,"d MMM yy")})]})}),(0,jn.jsx)(la,{className:"w-auto p-0",align:"start",children:(0,jn.jsx)(Ts,{mode:"single",selected:S.startDate,onSelect:e=>e&&Ee(e),className:"p-3 pointer-events-auto"})})]})]}),(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Start time"}),(0,jn.jsx)(zl,{value:S.startTime,onChange:e=>I(t=>{const r=Hl(t),a=r.end.getTime()-r.start.getTime(),s={...t,startTime:e};if(a<=0)return s;const n=new Date(Hl(s).start.getTime()+a);return{...s,endDate:Ne(n),endTime:Kl(n)}})})]}),(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"End date"}),(0,jn.jsxs)(ca,{children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",className:"w-full justify-start text-left text-sm font-normal h-9 px-2 gap-1","aria-label":`End date, ${y(S.endDate,"d MMMM yyyy")}`,children:[(0,jn.jsx)(K,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),(0,jn.jsx)("span",{className:"truncate",children:y(S.endDate,"d MMM yy")})]})}),(0,jn.jsx)(la,{className:"w-auto p-0",align:"start",children:(0,jn.jsx)(Ts,{mode:"single",selected:S.endDate,onSelect:e=>e&&I(t=>({...t,endDate:e})),className:"p-3 pointer-events-auto"})})]})]}),(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"End time"}),(0,jn.jsx)(zl,{value:S.endTime,onChange:e=>I(t=>({...t,endTime:e}))})]})]}),Ce&&(0,jn.jsx)("p",{className:"text-xs text-destructive",role:"alert",children:Ce})]}),(0,jn.jsxs)("div",{children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[S.isMeeting&&"onetap"===S.meetingProvider?(0,jn.jsx)(le,{className:"h-3.5 w-3.5"}):(0,jn.jsx)(q,{className:"h-3.5 w-3.5"}),S.isMeeting&&"onetap"===S.meetingProvider?"Meeting link":"Location"]}),S.isMeeting&&"onetap"===S.meetingProvider&&S.location.trim()?(0,jn.jsxs)("div",{className:"flex items-start gap-2 rounded-md border border-input bg-muted/30 min-h-9 p-2 w-full",children:[(0,jn.jsx)(le,{className:"h-3.5 w-3.5 text-primary shrink-0 mt-0.5"}),(0,jn.jsx)("a",{href:S.location,target:"_blank",rel:"noopener noreferrer",className:"flex-1 min-w-0 text-xs sm:text-sm text-primary hover:underline break-all leading-snug",title:S.location,children:S.location}),(0,jn.jsxs)("div",{className:"flex shrink-0 gap-0.5",children:[(0,jn.jsx)(Ye,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(S.location).then(()=>Ae.success(h("cal.meeting_link_copied")),()=>Ae.error(h("cal.copy_link_failed")))},title:h("cal.copy_meeting_link"),"aria-label":h("cal.copy_meeting_link"),
2children:(0,jn.jsx)(ye,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),(0,jn.jsx)(Ye,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>window.open(S.location,"_blank","noopener,noreferrer"),title:h("cal.open_meeting_link"),"aria-label":h("cal.open_meeting_link"),children:(0,jn.jsx)(L,{className:"h-3.5 w-3.5","aria-hidden":"true"})})]})]}):(0,jn.jsx)(Et,{value:S.location,onChange:e=>I(t=>({...t,location:e.target.value})),placeholder:S.isMeeting&&"onetap"===S.meetingProvider?"Will be auto-generated on save":"Add location or meeting URL",readOnly:S.isMeeting&&"onetap"===S.meetingProvider,className:"h-9 text-sm"})]}),Se&&(0,jn.jsxs)("div",{className:"rounded-lg border border-border bg-card p-3 space-y-2",children:[(0,jn.jsxs)("div",{className:"flex items-start gap-3",children:[(0,jn.jsx)("div",{className:"p-1.5 rounded-md bg-primary/10 shrink-0",children:(0,jn.jsx)(le,{className:"h-4 w-4 text-primary"})}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)(na,{className:"text-sm font-medium block",children:"Send AI notetaker"}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Joins the meeting, records and transcribes it, then drops a summary and action items in Project Settings â Meeting Bot."})]}),(0,jn.jsx)(sa,{checked:S.sendBot,onCheckedChange:e=>{pe.current=!0,I(t=>({...t,sendBot:e}))},"aria-label":"Send AI notetaker"})]}),S.sendBot&&(0,jn.jsxs)("p",{className:"pl-10 text-xs text-muted-foreground",children:[S.recurrence?"Repeating meeting: every occurrence in the next 30 days gets a notetaker, and later ones are added automatically. ":"","Credits are used only when the notetaker joins a meeting."]}),Ie.length>0&&(0,jn.jsxs)("p",{className:"pl-10 text-xs text-muted-foreground","data-testid":"upcoming-notetakers",children:[1===Ie.length?`1 upcoming meeting has a notetaker scheduled (${he(Ie[0].scheduled_at)}).`:`${Ie.length} upcoming meetings have a notetaker scheduled (next: ${he(Ie[0].scheduled_at)}).`," ","Manage them in Meetings."]}),S.sendBot&&(0,jn.jsxs)("div",{className:"pl-10",children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Bot name (shown in meeting)"}),(0,jn.jsx)(Et,{value:S.botName,onChange:e=>I(t=>({...t,botName:e.target.value})),placeholder:"1tab.ai Notetaker",className:"mt-1 h-8 text-sm"})]})]}),(0,jn.jsxs)("div",{children:[(0,jn.jsx)(na,{className:"text-xs text-muted-foreground",children:"Description"}),(0,jn.jsx)(Hr,{value:S.description,onChange:e=>I(t=>({...t,description:e.target.value})),placeholder:"Add notes or description",rows:3,className:"mt-1 text-sm"})]}),(0,jn.jsxs)("div",{children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,jn.jsx)(Q,{className:"h-3.5 w-3.5"}),"Color"]}),(0,jn.jsx)("div",{className:"flex gap-2.5 mt-1.5",children:$l.map(e=>(0,jn.jsx)("button",{type:"button",onClick:()=>I(t=>({...t,color:e})),"aria-label":`Color: ${e}`,"aria-pressed":S.color===e,className:He("w-8 h-8 rounded-full border-2 transition-all",Pi[e].dot,S.color===e?"border-foreground scale-110 shadow-md":"border-transparent opacity-60 hover:opacity-100 hover:scale-105")},e))})]}),(0,jn.jsxs)("div",{className:"rounded-lg border border-border bg-muted/20 p-3 space-y-2",children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,jn.jsx)(x,{className:"h-3.5 w-3.5"}),"Repeat"]}),(0,jn.jsx)(Tl,{value:S.recurrence,onChange:e=>I(t=>({...t,recurrence:e})),anchorDate:S.startDate})]}),(0,jn.jsxs)("div",{children:[(0,jn.jsxs)(na,{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[(0,jn.jsx)($e,{className:"h-3.5 w-3.5"}),"Reminder"]}),(0,jn.jsxs)(aa,{value:S.reminder,onValueChange:e=>I(t=>({...t,reminder:e})),children:[(0,jn.jsx)(ea,{className:"h-9 text-sm mt-1",children:(0,jn.jsx)(Xr,{})}),(0,jn.jsx)(ta,{children:Fl.map(e=>(0,jn.jsx)(ra,{value:e.value,children:e.label},e.value))})]})]}),B.length>0&&(0,jn.jsxs)("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-1",children:[(0,jn.jsxs)("p",{className:"text-xs font-medium text-amber-700 dark:text-amber-400",children:["Overlaps ",B.length," other event",B.length>
21?"s":"",":"]}),(0,jn.jsxs)("ul",{className:"text-xs text-amber-700 dark:text-amber-400 space-y-0.5",children:[B.slice(0,3).map(e=>(0,jn.jsxs)("li",{className:"truncate",children:["⢠",e.title," (",y(new Date(e.start_time),"h:mm a")," â ",y(new Date(e.end_time),"h:mm a"),")"]},`${e.id}-${e.start_time}`)),B.length>3&&(0,jn.jsxs)("li",{className:"text-amber-700/70 dark:text-amber-400/70",children:["â¦and ",B.length-3," more"]})]})]})]}),(0,jn.jsxs)(pt,{className:"flex flex-row items-center justify-between gap-2 pt-2 border-t border-border sm:justify-between",children:[(0,jn.jsx)("div",{className:"flex-shrink-0",children:v&&s?(0,jn.jsxs)(ca,{open:T,onOpenChange:A,children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsx)(Ye,{variant:"destructive",size:"icon",onClick:()=>A(!0),disabled:C,className:"h-9 w-9","aria-label":h("cal.delete_event"),title:h("cal.delete_event"),children:(0,jn.jsx)(f,{className:"h-4 w-4","aria-hidden":"true"})})}),(0,jn.jsxs)(la,{align:"start",className:"w-56 p-3",children:[(0,jn.jsx)("p",{className:"text-sm font-medium mb-3",children:"Do you want to delete?"}),(0,jn.jsxs)("div",{className:"flex gap-2 justify-end",children:[(0,jn.jsx)(Ye,{variant:"outline",size:"sm",onClick:()=>A(!1),disabled:C,children:"No"}),(0,jn.jsx)(Ye,{variant:"destructive",size:"sm",onClick:()=>{A(!1),(async()=>{n&&s&&(E(!0),await s(n.id),E(!1),t())})()},disabled:C,children:"Yes"})]})]})]}):null}),(0,jn.jsxs)("div",{className:"flex gap-2 items-center",children:[(0,jn.jsx)(Ye,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),(0,jn.jsx)(Ye,{size:"sm",onClick:async()=>{if(!S.title.trim()||C)return;const e=ql(S);if(e)return void Ae.error(e);E(!0);let s=S.location;if(S.isMeeting&&"onetap"===S.meetingProvider&&!S.location.trim()){const e=await(async()=>{const e=[0,3e3,6e3];let t="";for(let a=0;a<3;a++){e[a]>0&&await new Promise(t=>setTimeout(t,e[a]));try{const{data:{user:e}}=await Lt.auth.getUser(),r=e?.user_metadata?.display_name||e?.user_metadata?.full_name||void 0,{data:s,error:i}=await Lt.functions.invoke("create-meeting",{body:{title:S.title.trim()||"Meeting",attendeeCount:S.attendees.length,projectId:u,displayName:r,calendarEventId:v&&n?n.id:void 0}});if(!i&&s&&!s.error&&s.joinUrl)return s.joinUrl;let o=!1,l="";if(s?.error)l=s.error,o=!!s.serviceDown;else if(i){const e=i.context;if(e?.response&&"function"==typeof e.response.text)try{const t=await e.response.text();try{const r=JSON.parse(t);l=r.error||r.message||t,o=!!r.serviceDown||503===e.response.status}catch{l=t.slice(0,200),o=503===e.response.status}}catch{l=i.message||"Unknown error"}else l=i.message||"Unknown error"}if(t=l,Ge.error(`create-meeting attempt ${a+1}/3 failed:`,{error:i,data:s,detail:l,serviceDown:o}),!o||2===a)break;Ae.info(h("cal.meeting_service_warming"),{duration:2500})}catch(r){if(t=r?.message||"Network error",Ge.error(`create-meeting attempt ${a+1}/3 threw:`,r),2===a)break}}return Ae.error(t?h("cal.meeting_room_failed_reason",{reason:t}):h("cal.meeting_room_failed"),{duration:8e3}),null})();if(e)s=e,Ae.success(h("cal.meeting_room_created"));else{if(E(!1),!(await p({title:"Couldn't create the meeting room",description:"Save the event without a meeting link? You can retry later by reopening the event.",confirmLabel:"Save without link"})))return;s="",E(!0)}}const{start:i,end:o}=Hl(S),l={title:S.title.trim(),start_time:i.toISOString(),end_time:o.toISOString(),description:S.description,location:s,attendees:S.attendees.map(e=>({email:e})),is_all_day:S.isAllDay,color:S.color,recurrence_rule:S.recurrence,reminder_minutes:"-1"!==S.reminder?parseInt(S.reminder,10):void 0,time_zone:An()||void 0};if(v&&a&&n&&Wi(n.id))return re({input:l,locationToSave:s,startDtIso:i.toISOString()}),void E(!1);let c=!0,d=null;if(v&&a&&n)c=await a(n.id,l),d=Fi(n.id);else{const e=await r(l);c=!!e,d=e?.id??null}if(c&&d){const e=d;(async()=>{const t=await xe();t.sync&&await fe(e,t.enabled,{includeInProgress:!0})})()}E(!1),c&&t()},disabled:C||!S.title.trim()||!!Ce,children:C?S.isMeeting&&"onetap"===S.meetingProvider?"Creating meeting...":"Saving...":v?"Update":"Create"})]})]})]}),te&&(0,jn.jsx)(wl,{open:!0,action:"edit",onClose:()=>re(null),onConfirm:async e=>{if(!te||!n||!a)return void re(null);E(!0);const{input:r,startDtIso:s}=te,i={...r,original_start:n.start_time},o=new Date(Date.now()-6e5).toISOString(),l=await a(n.id,i,e);l&&(async(e,t,r)=>{if(!n)return;const a=Fi(n.id),s=await xe();if("all"===e)return void(s.sync&&await fe(a,s.enabled,{includeInProgress:!0}));const i=await yi({seriesId:a,userId:n.user_id,projectId:n.project_id,startIso:t,recurring:"this_and_following"===e,createdAfterIso:r});i?(s.hadNotetaker&&await fe(a,void 0,{includeInProgress:!1,quiet:!0}),!0===s.enabled&&await fe(i,!0,{includeInProgress:!0})):s.sync&&await fe(a,s.enabled,{includeInProgress:!0})})(e,s,o),E(!1),re(null),l&&t()}})]})}var Bl=it(()=>qe(()=>import("./AssadVoiceMode-CT4anZCz.js").then(e=>({default:e.AssadVoiceMode})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]))),Gl={a:({href:e,children:t})=>{const r="string"==typeof e&&/^(https?:|mailto:)/i.test(e)?e:void 0;return(0,jn.jsx)("a",{href:r,target:"_blank",rel:"noopener noreferrer",children:t})},img:({src:e,alt:t})=>(0,jn.jsx)(Br,{src:e,alt:t})},Yl=[{value:"too_long",labelKey:"pa.feedback_too_long"},{value:"wrong_info",labelKey:"pa.feedback_wrong_info"},{value:"didnt_do_it",labelKey:"pa.feedback_didnt_do_it"},{value:"other",labelKey:"pa.feedback_other"}],Jl=fn.memo(function({msg:e,avatarEmoji:t,feedback:r,isStreamingNow:a,onCreateTask:s,onLogDecision:n,onScheduleMeeting:o,onFeedback:l,onTogglePin:c,onProactiveReply:d,registerUnreadElement:u}){const{t:m}=at(),p="assistant"===e.role?function(e){if(!e)return[];const t=e.length>8e3?e.slice(0,8e3):e,r=[],a=new Set;for(const{re:s,build:n}of Jo){const e=s.exec(t);if(!e)continue;const i=n(e);if(!i)continue;const o=`${i.kind}:${i.count??i.module}`;
2a.has(o)||(a.add(o),r.push(i))}for(const{re:s,module:n,label:i}of Qo)if(s.test(t)&&!r.find(e=>"module"===e.kind&&e.module===n)){r.push({kind:"module",label:i,module:n});break}return r.slice(0,4)}(e.content).filter(e=>null!==Zo(e)):[],h="assistant"===e.role&&!0===e.metadata?.proactive,f="assistant"===e.role&&!e.read_at,[g,x]=(0,fn.useState)(!1),[_,b]=(0,fn.useState)(!1),j=(0,fn.useRef)(null);return(0,fn.useEffect)(()=>{if(!f||!u)return;const t=j.current;return u(e.id,t),()=>u(e.id,null)},[f,e.id,u]),(0,jn.jsxs)("div",{ref:j,className:"group",children:[(0,jn.jsxs)("div",{className:He("flex gap-2","user"===e.role?"justify-end":"justify-start"),children:["assistant"===e.role&&(0,jn.jsx)("span",{className:"shrink-0 mt-0.5",children:e.pinned?(0,jn.jsx)("span",{className:"text-base",children:"ð"}):(0,jn.jsx)(Or,{value:t,size:"base"})}),(0,jn.jsxs)("div",{className:He("rounded-2xl px-3 py-2 max-w-[85%]","user"===e.role?"bg-primary text-primary-foreground":"bg-ai/10 border border-ai/20 text-foreground",h&&"border-ai/40 bg-gradient-to-br from-ai/10 to-ai-glow/15"),children:[h&&(0,jn.jsxs)("p",{className:"text-[10px] font-bold uppercase tracking-wider text-ai mb-1",children:["ð¡ ",m("pa.proactive_insight")]}),"assistant"===e.role?(0,jn.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none [&>p]:my-0.5 text-sm break-words",children:(0,jn.jsx)(Vr,{components:Gl,children:e.content})}):(0,jn.jsx)("p",{className:"text-sm whitespace-pre-wrap",children:e.content}),h&&e.metadata?.prefilled_prompt&&d&&(0,jn.jsxs)("button",{onClick:()=>d(e),className:"mt-2 inline-flex items-center gap-1 text-xs font-semibold text-ai hover:text-ai/80 transition-colors",children:["ð¬ ",m("pa.ask_about",{name:String(e.metadata.coach_name||m("pa.follow_more"))})," â"]})]})]}),"assistant"===e.role&&p.length>0&&(0,jn.jsx)("div",{className:"ml-7 mt-0.5 flex flex-wrap items-center gap-1",children:p.map((t,r)=>(0,jn.jsx)("button",{onClick:()=>function(e){window.dispatchEvent(new CustomEvent("pa:navigate-citation",{detail:e}));const t=Zo(e);t&&window.dispatchEvent(new CustomEvent("navigate-to-module",{detail:{module:t}}))}(t),className:"inline-flex items-center gap-1 rounded-full border border-ai/30 bg-ai/5 hover:bg-ai/15 text-xs text-foreground/80 px-2 py-0.5 transition-colors",title:m("pa.source_jump"),children:t.label},`${e.id}-chip-${r}`))}),"assistant"===e.role&&(0,jn.jsxs)("div",{className:"ml-7 mt-0.5 flex items-center gap-1",children:[(0,jn.jsx)(cl,{message:e.content,onCreateTask:s,onLogDecision:n,onScheduleMeeting:o}),!a&&(0,jn.jsxs)("div",{className:He("flex items-center gap-0.5 ml-1 transition-opacity focus-within:opacity-100 sm:group-hover:opacity-100",r?"opacity-100":"opacity-100 sm:opacity-0"),children:[(0,jn.jsx)("button",{onClick:()=>{x(!1),l(e.id,"up")},className:He("p-0.5 rounded hover:bg-muted-foreground/10 transition-colors","up"===r?"text-success":"text-muted-foreground/40 hover:text-muted-foreground"),title:m("pa.helpful"),children:(0,jn.jsx)($,{className:"h-3 w-3"})}),(0,jn.jsx)("button",{onClick:()=>{l(e.id,"down"),b(!1),x(!0)},className:He("p-0.5 rounded hover:bg-muted-foreground/10 transition-colors","down"===r?"text-destructive":"text-muted-foreground/40 hover:text-muted-foreground"),title:m("pa.not_helpful"),children:(0,jn.jsx)(i,{className:"h-3 w-3"})}),(0,jn.jsx)("button",{onClick:()=>c(e.id,!e.pinned),className:He("p-0.5 rounded hover:bg-muted-foreground/10 transition-colors",e.pinned?"text-primary":"text-muted-foreground/40 hover:text-muted-foreground"),title:e.pinned?m("pa.unpin"):m("pa.pin_answer"),children:(0,jn.jsx)(ue,{className:"h-3 w-3"})}),(0,jn.jsx)(ml,{text:e.content})]})]}),"assistant"===e.role&&g&&"down"===r&&(0,jn.jsx)("div",{className:"ml-7 mt-1 flex flex-wrap items-center gap-1",children:_?(0,jn.jsx)("span",{className:"text-[10px] text-muted-foreground",children:m("pa.feedback_thanks")}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("span",{className:"text-[10px] text-muted-foreground mr-0.5",children:m("pa.feedback_question")}),Yl.map(t=>(0,jn.jsx)("button",{onClick:()=>{l(e.id,"down",t.value),b(!0)},className:"px-2 py-0.5 text-[10px] rounded-full border border-border bg-muted/40 text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",children:m(t.labelKey)},t.value))]})})]})}),Ql={[jt.IDEATION]:"pa.guide_ideation",[jt.MARKET_RESEARCH]:"pa.guide_market_research",[jt.CUSTOMER_DISCOVERY]:"pa.guide_customer_discovery",[jt.STRATEGY]:"pa.guide_strategy",[jt.PRODUCT]:"pa.guide_product",[jt.MARKETING]:"pa.guide_marketing",[jt.FINANCIALS]:"pa.guide_financials",[jt.TEAM]:"pa.guide_team",[jt.PITCH_DECK]:"pa.guide_pitch_deck",[jt.FUNDRAISING]:"pa.guide_fundraising",[jt.TASKS]:"pa.guide_tasks",[jt.OKRS]:"pa.guide_okrs"};var Zl=(0,fn.forwardRef)(function({projectId:t,onBack:r,voiceMode:a,onVoiceModeChange:n,globalVoiceActive:i,onPopOutVoice:o,activeModule:l,isNewProject:c,hideHeader:d,showSearch:u,onShowSearchChange:m,searchQuery:g,onSearchQueryChange:x,showPinnedOnly:_,onShowPinnedOnlyChange:b,onPinnedCountChange:v,showPreferences:y,onShowPreferencesChange:N,pendingPrompt:S,onPendingPromptConsumed:E},T){const{t:A}=at(),{preferences:D,updatePreference:O}=oo(t),R=Kt(),[M,P]=(0,fn.useState)(null),{messages:L,loading:U,streaming:$,statusText:F,settings:H,feedbackMap:q,sendMessage:z,clearHistory:V,stopStreaming:B,refreshMessages:G,submitFeedback:Y,appendLocalAssistantMessage:Q,togglePin:Z,pendingDelete:X,cancelDelete:ee,pendingConfirm:te,confirmOutwardAction:re,cancelConfirm:ae,hasMoreOlder:ne,loadingOlder:oe,loadOlderMessages:le,markMessagesRead:ce}=Yo(t,D,M),[me,pe]=(0,fn.useState)(!1),[he,ge]=(0,fn.useState)(null),[xe,_e]=(0,fn.useState)(!1),be=D.selected_avatar||H.avatar_emoji,je=(0,fn.useMemo)(()=>
2{if(!c)return null;const e=l&&Ql[l]||Ql[jt.IDEATION];return e?A(e):null},[c,l,A]),[ve,ye]=(0,fn.useState)(null),{createTask:Ne}=ka(t),{isViewer:ke}=bn(t),{createEvent:Se}=Qi(),[Ie,Ce]=(0,fn.useState)(""),[Ee,Te]=(0,fn.useState)(!1),Oe=a??Ee,Re=n??Te,Me=(0,fn.useRef)(null),Pe=(0,fn.useRef)(null),[Le,Ue]=(0,fn.useState)({}),[$e,Fe]=(0,fn.useState)(!1),[We,Ke]=(0,fn.useState)(""),[ze,Ve]=(0,fn.useState)(()=>"undefined"==typeof navigator||navigator.onLine);(0,fn.useEffect)(()=>{const e=()=>Ve(!0),t=()=>Ve(!1);return window.addEventListener("online",e),window.addEventListener("offline",t),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",t)}},[]);const[Be,Je]=(0,fn.useState)(!1),Qe=(0,fn.useRef)(0),[Ze,et]=(0,fn.useState)(""),[tt,rt]=(0,fn.useState)(!1),[st,nt]=(0,fn.useState)(!1),it=void 0!==g?g:Ze,ot=void 0!==u?u:tt,lt=void 0!==_?_:st,ct=(0,fn.useCallback)(e=>{x?x(e):et(e)},[x]),dt=(0,fn.useCallback)(e=>{m?m(e):rt(e)},[m]),ut=(0,fn.useCallback)(e=>{b?b(e):nt(e)},[b]),mt=(0,fn.useMemo)(()=>{let e=L;lt&&(e=e.filter(e=>e.pinned));const t=it.trim().toLowerCase();return t&&(e=e.filter(e=>e.content.toLowerCase().includes(t))),e},[L,it,lt]),pt=(0,fn.useMemo)(()=>L.filter(e=>e.pinned).length,[L]),ht=(0,fn.useMemo)(()=>{if($||0===L.length)return[];const e=L[L.length-1];return e&&"assistant"===e.role?e.metadata?.ephemeral||e.metadata?.proactive?[]:function(e,t){const r=e.toLowerCase();return/\b(task|to-?do|action item|checklist|next step)\b/.test(r)?[t("pa.follow_tasks"),t("pa.follow_prioritize")]:/\b(meeting|call|sync|standup|1[:-]?1)\b/.test(r)?[t("pa.follow_prep"),t("pa.follow_calendar")]:/\b(deal|pipeline|crm|contact|lead|prospect)\b/.test(r)?[t("pa.follow_stale_deals"),t("pa.follow_pipeline")]:/\b(okr|objective|key result|goal|target)\b/.test(r)?[t("pa.follow_okr_risk"),t("pa.follow_update_progress")]:r.trim().endsWith("?")?[t("pa.follow_yes"),t("pa.follow_not_now")]:[t("pa.follow_more"),t("pa.follow_summarize"),t("pa.follow_next")]}(e.content,A):[]},[L,$,A]);(0,fn.useEffect)(()=>{v?.(pt)},[pt,v]),(0,fn.useImperativeHandle)(T,()=>({clearHistory:()=>pe(!0)}),[]);const[ft,gt]=(0,fn.useState)(!1),xt=void 0!==y?y:ft,bt=(0,fn.useCallback)(e=>{N?N(e):gt(e)},[N]),[Tt,At]=(0,fn.useState)(!1),[Dt,Ot]=(0,fn.useState)(!1),[Rt,Mt]=(0,fn.useState)(!1),[Pt,Lt]=(0,fn.useState)(!1),[Ut,$t]=(0,fn.useState)(!1),[Ft,Wt]=(0,fn.useState)(""),[Ht,qt]=(0,fn.useState)(""),[zt,Vt]=(0,fn.useState)(""),Bt=(0,fn.useRef)($);Bt.current=$;const Gt=(0,fn.useRef)(M);Gt.current=M;const Yt=(0,fn.useRef)(z);Yt.current=z;const Jt=(0,fn.useRef)(Q);Jt.current=Q;const Qt=(0,fn.useRef)(new Set);(0,fn.useEffect)(()=>{!S||U||$||Qt.current.has(S.id)||(Qt.current.add(S.id),E?.(S.id),Yt.current(S.text,"chat",void 0,void 0,Gt.current))},[S,U,$,E]),(0,fn.useEffect)(()=>{const e=e=>{const t=e.detail;t?.threadId&&Gt.current===t.threadId?P(null):G()};return window.addEventListener("pa:thread-archived",e),()=>{window.removeEventListener("pa:thread-archived",e)}},[G]);const Zt=(0,fn.useRef)(null),Xt=(0,fn.useMemo)(()=>[`ð§ ${A("pa.nudge_water_1")}`,`ð§ ${A("pa.nudge_break_1")}`,`ð§ ${A("pa.nudge_water_2")}`,`â ${A("pa.nudge_break_2")}`,`ð§ ${A("pa.nudge_water_3")}`,`ð§ ${A("pa.nudge_breathe")}`],[A]);(0,fn.useEffect)(()=>{if(D.break_reminders_enabled)return Zt.current=setInterval(()=>{if(Bt.current)return;const e=Xt[Math.floor(Math.random()*Xt.length)];Jt.current(e)},27e5),()=>{Zt.current&&clearInterval(Zt.current)};Zt.current&&clearInterval(Zt.current)},[D.break_reminders_enabled,Xt]);const[er,tr]=(0,fn.useState)([]),rr=(0,fn.useRef)(null);(0,fn.useEffect)(()=>{rr.current=null,tr([])},[t]),(0,fn.useEffect)(()=>{if(!c||!l)return;if(rr.current===l)return;if(null===rr.current)return void(rr.current=l);rr.current=l;const e=Ql[l];e&&tr(t=>[...t,{id:crypto.randomUUID(),content:A(e)}])},[c,l,A]);const ar=(0,fn.useRef)(!0),sr=(0,fn.useCallback)(()=>{const e=Me.current;return e?e.querySelector("[data-radix-scroll-area-viewport]"):null},[]);(0,fn.useEffect)(()=>{if(!ar.current)return;const e=sr();e&&(e.scrollTop=e.scrollHeight)},[L,ve]),(0,fn.useEffect)(()=>
2{if(U)return;ar.current=!0;const e=()=>{const e=sr();e&&(e.scrollTop=e.scrollHeight)};e();const t=setTimeout(e,50);return()=>clearTimeout(t)},[U,M]),(0,fn.useEffect)(()=>{if(!Oe||!o)return;const e=()=>{"hidden"===document.visibilityState&&(Re(!1),o(Gt.current))};return document.addEventListener("visibilitychange",e),()=>document.removeEventListener("visibilitychange",e)},[Oe,o,Re]),(0,fn.useEffect)(()=>{Oe||ye(null)},[Oe]);const nr=async()=>{const t=Ie.trim();if(!t||$)return;Ce(""),Fe(!1);const r=e=>{e||Ce(e=>e||t)};if(function(e){const t=e.toLowerCase();return/\b(look at|see|show|view|read|check|what('?s| is) on)\b.*(screen|page|view|display|dashboard|module|tab)/i.test(t)||/\bwhat (do |can )?you see\b/i.test(t)||/\bcan you see (this|my|the|what)/i.test(t)||/\bscreenshot\b/i.test(t)}(t))try{const a=await async function(){const{default:t}=await qe(async()=>{const{default:t}=await import("./html2canvas-BZeoWjzY.js").then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([48,1])),r=await t(document.querySelector("main")||document.body,{useCORS:!0,allowTaint:!0,scale:1,logging:!1,ignoreElements:e=>{const t=e.classList;if(!t)return!1;if("INPUT"===e.tagName){const t=e.type;if("password"===t||"hidden"===t)return!0;const r=e.autocomplete||"";if(r.includes("password")||"cc-number"===r||"cc-csc"===r)return!0;if(e.hasAttribute("data-private"))return!0}return!!(e.hasAttribute&&e.hasAttribute("data-private")||t.contains("voice-floating-widget")||t.contains("sonner-toaster")||"dialog"===e.getAttribute("role")||"DIALOG"===e.tagName||"voice-overlay"===e.id||t.contains("fixed")||t.contains("absolute")&&e.parentElement===document.body)}});let a=r;if(r.width>Xo){const e=Xo/r.width,t=document.createElement("canvas");t.width=Xo,t.height=Math.round(r.height*e);const s=t.getContext("2d");s&&(s.drawImage(r,0,0,t.width,t.height),a=t)}const s=a.toDataURL("image/jpeg",.6);return s.split(",")[1]||s}();return void r(await z(t,"chat",a,void 0,M))}catch(a){Ge.warn("Screen capture failed:",a)}r(await z(t,"chat",void 0,void 0,M))},ir=(0,fn.useCallback)(e=>{Wt(e.slice(0,200)),At(!0)},[]),or=(0,fn.useCallback)(e=>{qt(e.slice(0,200)),Vt("From assistant conversation"),Ot(!0)},[]),lr=(0,fn.useCallback)(e=>{Mt(!0)},[]),cr=(0,fn.useCallback)((e,t,r)=>{Ue(r=>({...r,[e]:t})),Y(e,t,r)},[Y]),dr=(0,fn.useCallback)(e=>{const t=e.metadata?.prefilled_prompt;t&&"string"==typeof t&&z(t,"chat",void 0,void 0,M)},[z,M]),ur=(0,fn.useRef)(new Set),mr=(0,fn.useRef)(null),pr=(0,fn.useRef)(null),hr=(0,fn.useRef)(new WeakMap),fr=(0,fn.useRef)(new Map),gr=(0,fn.useRef)(new Map),xr=(0,fn.useRef)(ce);xr.current=ce;const _r=(0,fn.useCallback)(()=>{mr.current||(mr.current=setTimeout(()=>{mr.current=null;const e=Array.from(ur.current);0!==e.length&&(ur.current.clear(),xr.current(e))},300))},[]);(0,fn.useEffect)(()=>{if("undefined"==typeof IntersectionObserver)return;const e=new IntersectionObserver(e=>{for(const t of e){const e=hr.current.get(t.target);if(!e)continue;const r=fr.current.get(e);if(t.isIntersecting&&t.intersectionRatio>=.5){if(r)continue;const t=setTimeout(()=>{fr.current.delete(e),ur.current.add(e),_r()},500);fr.current.set(e,t)}else r&&(clearTimeout(r),fr.current.delete(e))}},{threshold:[0,.5,1]});return pr.current=e,()=>{e.disconnect(),pr.current=null;for(const e of fr.current.values())clearTimeout(e);fr.current.clear(),gr.current.clear(),mr.current&&(clearTimeout(mr.current),mr.current=null)}},[_r]);const br=(0,fn.useCallback)((e,t)=>{const r=pr.current;if(!r)return;const a=gr.current.get(e),s=fr.current.get(e);s&&(clearTimeout(s),fr.current.delete(e)),a&&(r.unobserve(a),gr.current.delete(e)),t&&(hr.current.set(t,e),gr.current.set(e,t),r.observe(t))},[]),jr=(0,fn.useMemo)(()=>function(e,t,r,a){const s=(new Date).getHours(),n=(new Date).getDay(),i=s>=6&&s<13,o=s>=17,l=5===n,c=[];i&&1===n&&c.push({label:"Plan my week",prompt:"",isSpecialType:"weekly_plan"}),i&&c.push({label:"Brief me",prompt:"",isSpecialType:"briefing"}),e&&xl[e]&&c.push(...xl[e]),o&&l&&c.push({label:"Week wrap-up",prompt:"Run my end-of-week review. What did we accomplish toward OKRs? Top 3 priorities next week?"}
2),o&&c.push({label:"End of Day",prompt:"",isSpecialType:"end_of_day"}),e!==jt.CALENDAR&&e!==jt.MEETINGS&&c.push({label:"Meeting prep",prompt:"",isSpecialType:"prepare_meeting"});const d=new Set;return c.filter(e=>!d.has(e.label)&&(d.add(e.label),!0)).slice(0,3).map(e=>({label:e.label,action:()=>{e.isSpecialType?t("",e.isSpecialType,void 0,void 0,a):e.prompt?t(e.prompt,"chat",void 0,void 0,a):r("/")}}))}(l,z,Ce,M).map(e=>{return{...e,rawLabel:e.label,label:A((t=e.label,`pa.qa_${t.toLowerCase().replace(/what's/g,"whats").replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")}`)),icon:(()=>{switch(e.label){case"Brief me":default:return se;case"Standup":case"Post to team":case"This week":return De;case"Top 3 Today":return j;case"What's blocking?":case"Stale deals":return C;case"OKR health":case"Plan my week":case"Forecast":case"YTD summary":return W;case"Meeting prep":return K;case"End of Day":case"Week wrap-up":return fe;case"Search":return k}})()};var t}),[l,z,Ce,M,A]);return U?(0,jn.jsx)("div",{className:"flex items-center justify-center h-full",children:(0,jn.jsx)(Xe,{})}):(0,jn.jsxs)("div",{className:"flex flex-col h-full max-h-[100dvh] overflow-hidden bg-background relative",onDragEnter:e=>{e.dataTransfer?.types?.includes("Files")&&(e.preventDefault(),Qe.current+=1,Je(!0))},onDragOver:e=>{e.dataTransfer?.types?.includes("Files")&&e.preventDefault()},onDragLeave:e=>{e.preventDefault(),Qe.current=Math.max(0,Qe.current-1),0===Qe.current&&Je(!1)},onDrop:e=>{var r;e.dataTransfer?.files?.length&&(e.preventDefault(),Qe.current=0,Je(!1),(r=Array.from(e.dataTransfer.files)).length&&t&&(_e(!1),ge(r)))},children:[Be&&(0,jn.jsx)("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-primary/10 border-2 border-dashed border-primary pointer-events-none",children:(0,jn.jsxs)("div",{className:"text-center px-4 py-3 rounded-lg bg-background/90 shadow-lg",children:[(0,jn.jsxs)("p",{className:"text-sm font-semibold text-primary",children:["ð ",A("pa.drop_dataroom")]}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:A("pa.drop_dataroom_desc")})]})}),!d&&(0,jn.jsxs)("div",{className:"px-3 py-2 border-b border-border flex items-center gap-2 shrink-0",children:[r&&(0,jn.jsx)(Ye,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:r,title:A("action.back"),"aria-label":A("action.back"),children:(0,jn.jsx)(I,{className:"h-4 w-4"})}),(0,jn.jsx)(Or,{value:be,size:"xl"}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("h3",{className:"font-semibold text-sm text-foreground",children:H.display_name}),(0,jn.jsx)(gl,{projectId:t,currentThreadId:M,onThreadChange:P,onNewThread:()=>{P(function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=new Uint8Array(16);if("undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues)crypto.getRandomValues(e);else for(let r=0;r<e.length;r+=1)e[r]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}())}})]}),(0,jn.jsx)(Ye,{variant:"outline",size:"icon",className:"h-7 w-7 border-primary/30 bg-primary/5 hover:bg-primary/10 text-primary",onClick:()=>Re(!0),disabled:i,title:A("pa.start_voice"),"aria-label":A("pa.start_voice"),children:(0,jn.jsx)(we,{className:"h-3.5 w-3.5"})}),(0,jn.jsxs)(_a,{children:[(0,jn.jsx)(fa,{asChild:!0,children:(0,jn.jsx)(Ye,{variant:"ghost",size:"icon",className:He("h-7 w-7",ot||lt?"text-primary":"text-muted-foreground"),title:A("pa.more_options"),"aria-label":A("pa.more_options"),children:(0,jn.jsx)(p,{className:"h-3.5 w-3.5"})})}),(0,jn.jsxs)(ga,{align:"end",className:"w-52",children:[(0,jn.jsxs)(xa,{onClick:()=>{const e=!ot;dt(e),e||ct("")},children:[(0,jn.jsx)(k,{className:"h-4 w-4 mr-2"}),A(ot?"pa.hide_search":"pa.search_conversation")]}),pt>0&&(0,jn.jsxs)(xa,{onClick:()=>ut(!lt),children:[(0,jn.jsx)(ue,{className:"h-4 w-4 mr-2"}),lt?A("pa.show_all_messages"):A("pa.show_pinned_only",{count:pt})]}),(0,jn.jsxs)(xa,{onClick:()=>$t(!0),children:[(0,jn.jsx)(ie,{className:"h-4 w-4 mr-2"}),A("pa.capabilities")]}),(0,jn.jsxs)(xa,{onClick:()=>Lt(!0),children:[(0,jn.jsx)(h,{className:"h-4 w-4 mr-2"}),A("pa.audit_log")]}),(0,jn.jsxs)(xa,{onClick:()=>bt(!0),children:[(0,jn.jsx)(s,{className:"h-4 w-4 mr-2"}),A("pa.assistant_settings")]}),(0,jn.jsx)(pa,{}),(0,jn.jsxs)(xa,{onClick:()=>pe(!0),className:"text-destructive focus:text-destructive",children:[(0,jn.jsx)(f,{className:"h-4 w-4 mr-2"}),A("pa.clear_conversation")]})]})]})]}),ot&&(0,jn.jsx)("div",{className:"px-3 py-2 border-b border-border shrink-0 bg-muted/30",children:(0,jn.jsxs)("div",{className:"relative",children:[(0,jn.jsx)(k,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),(0,jn.jsx)(Et,{value:it,onChange:e=>ct(e.target.value),placeholder:A("pa.search_ph"),className:"pl-7 pr-8 h-8 text-xs",autoFocus:!0}),it&&(0,jn.jsx)("button",{type:"button",onClick:()=>ct(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",title:A("action.clear"),"aria-label":A("action.clear"),children:(0,jn.jsx)(J,{className:"h-3.5 w-3.5"})})]})}),(0,jn.jsx)(_t,{className:"flex-1 min-h-0 px-3",ref:Me,onScroll:e=>{const t=e.target;if(!t||!t.matches("[data-radix-scroll-area-viewport]"))return;const r=t.scrollHeight-(t.scrollTop+t.clientHeight);ar.current=r<120},children:(0,jn.jsxs)("div",{className:"py-3 space-y-3 max-w-2xl mx-auto",children:[(0,jn.jsx)(ks,{projectId:t}),(0,jn.jsx)(jl,{projectId:t}),(0,jn.jsx)(yl,{projectId:t}),ne&&(0,jn.jsx)("div",{className:"flex justify-center",children:(0,jn.jsx)(Ye,{variant:"ghost",size:"sm",className:"h-7 text-[11px] text-muted-foreground hover:text-foreground",onClick:le,disabled:oe,children:A(oe?"common.loading":"pa.load_older")})}),0===L.length&&!$&&(je?(0,jn.jsxs)("div",{className:"space-y-3",children:[(0,jn.jsxs)("div",{className:"flex gap-2 justify-start",children:[(0,jn.jsx)("span",{className:"shrink-0 mt-0.5",children:(0,jn.jsx)(Or,{value:be,size:"xl"})}),(0,jn.jsx)("div",{className:"max-w-[85%] rounded-2xl rounded-tl-sm px-3 py-2.5 bg-muted text-sm text-foreground",children:(0,jn.jsx)(Vr,{components:{p:({children:e})=>(0,jn.jsx)("p",{className:"mb-2 last:mb-0 leading-relaxed",children:e}),strong:({children:e})=>(0,jn.jsx)("strong",{className:"font-semibold text-foreground",children:e}),li:({children:e})=>(0,jn.jsx)("li",{className:"ml-4 list-disc leading-relaxed",children:e}),ol:({children:e})=>(0,jn.jsx)("ol",{className:"space-y-1 mb-2",children:e}),ul:({children:e})=>(0,jn.jsx)("ul",{className:"space-y-1 mb-2",children:e}),em:({children:e})=>(0,jn.jsx)("em",{className:"text-muted-foreground not-italic text-[11px]",children:e})},children:je})})]}),(0,jn.jsx)("p",{className:"text-[11px] text-muted-foreground text-center pt-1",children:A("pa.type_question")})]}):(0,jn.jsxs)("div",{className:"text-center py-8 space-y-4",children:[(0,jn.jsx)("span",{className:"block",children:(0,jn.jsx)(Or,{value:be,size:"4xl"})}),(0,jn.jsxs)("div",{children:[(0,jn.jsx)("h3",{className:"text-base font-semibold text-foreground mb-1",children:A("pa.empty_hi",{name:H.display_name})}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground max-w-xs mx-auto",children:A("pa.empty_desc")}),(0,jn.jsxs)("button",{onClick:()=>$t(!0),className:"mt-2 inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",children:[(0,jn.jsx)(ie,{className:"h-3.5 w-3.5"}),A("pa.see_capabilities")]})]}),(0,jn.jsxs)("div",{className:"flex flex-wrap justify-center gap-1.5",children:[(0,jn.jsxs)(Ye,{variant:"default",size:"sm",className:"gap-1.5 text-xs h-8",onClick:()=>Re(!0),disabled:i,children:[(0,jn.jsx)(we,{className:"h-3.5 w-3.5"}),A("pa.start_voice_chat")]}),jr.map(e=>(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",className:"gap-1.5 text-xs h-8",onClick:e.action,disabled:$,children:[(0,jn.jsx)(e.icon,{className:"h-3.5 w-3.5"}),e.label]},e.rawLabel))]})]})),mt.map((e,t)=>{const r=$&&"assistant"===e.role&&t===mt.length-1;return(0,jn.jsx)(Jl,{msg:e,avatarEmoji:be,feedback:Le[e.id]??q[e.id],isStreamingNow:r,onCreateTask:ke?void 0:ir,onLogDecision:or,onScheduleMeeting:lr,onFeedback:cr,onTogglePin:Z,onProactiveReply:dr,registerUnreadElement:br},e.id)}),ve&&(0,jn.jsxs)("div",{className:"flex gap-2 justify-start",children:[(0,jn.jsx)("span",{className:"shrink-0 mt-0.5",children:(0,jn.jsx)(Or,{value:be,size:"base"})}),(0,jn.jsx)("div",{className:"rounded-2xl px-3 py-2 max-w-[85%] bg-muted",children:(0,jn.jsx)("div",{className:"prose prose-sm dark:prose-invert max-w-none [&>p]:my-0.5 text-sm break-words",children:(0,jn.jsx)(Vr,{components:Gl,children:ve})})})]}),er.map(e=>(0,jn.jsxs)("div",{className:"flex gap-2 justify-start",children:[(0,jn.jsx)("span",{className:"shrink-0 mt-0.5",children:(0,jn.jsx)(Or,{value:be,size:"xl"})}),(0,jn.jsx)("div",{className:"max-w-[85%] rounded-2xl rounded-tl-sm px-3 py-2.5 bg-primary/10 border border-primary/20 text-sm text-foreground",children:(0,jn.jsx)(Vr,{components:{p:({children:e})=>(0,jn.jsx)("p",{className:"mb-2 last:mb-0 leading-relaxed",children:e}),strong:({children:e})=>(0,jn.jsx)("strong",{className:"font-semibold text-foreground",children:e}),li:({children:e})=>(0,jn.jsx)("li",{className:"ml-4 list-disc leading-relaxed",children:e}),ol:({children:e})=>(0,jn.jsx)("ol",{className:"space-y-1 mb-2",children:e}),ul:({children:e})=>(0,jn.jsx)("ul",{className:"space-y-1 mb-2",children:e}),em:({children:e})=>(0,jn.jsx)("em",{className:"text-muted-foreground not-italic text-[11px]",children:e})},children:e.content})})]},e.id)),$&&"assistant"!==L[L.length-1]?.role&&(0,jn.jsxs)("div",{className:"flex gap-2 items-center",children:[(0,jn.jsx)(Or,{value:be,size:"base"}),(0,jn.jsx)("div",{className:"bg-ai/10 border border-ai/20 rounded-2xl px-3 py-2",children:F?(0,jn.jsx)("p",{className:"text-xs text-ai animate-pulse",children:F}):(0,jn.jsxs)("div",{className:"flex gap-1",children:[(0,jn.jsx)("span",{className:"w-1.5 h-1.5 bg-ai rounded-full animate-bounce"}),(0,jn.jsx)("span",{className:"w-1.5 h-1.5 bg-ai rounded-full animate-bounce [animation-delay:0.15s]"}),(0,jn.jsx)("span",{className:"w-1.5 h-1.5 bg-ai rounded-full animate-bounce [animation-delay:0.3s]"})]})})]})]})}),ht.length>0?(0,jn.jsx)("div",{className:"px-3 pt-1.5 shrink-0",children:(0,jn.jsx)("div",{className:"flex flex-wrap gap-1.5 max-w-2xl mx-auto",children:ht.map(e=>(0,jn.jsx)("button",{onClick:()=>z(e,"chat",void 0,void 0,M),className:"px-2.5 py-1 text-[11px] font-medium rounded-full border border-ai/30 bg-ai/5 text-foreground
2/80 hover:bg-ai/15 hover:text-foreground transition-colors",children:e},e))})}):L.length>0&&!$?(0,jn.jsx)("div",{className:"px-3 py-1.5 border-t border-border shrink-0",children:(0,jn.jsx)("div",{className:"flex flex-wrap gap-1.5",children:jr.map(e=>(0,jn.jsxs)(Ye,{variant:"ghost",size:"sm",className:"gap-1 text-[11px] text-muted-foreground hover:text-foreground h-7",onClick:e.action,children:[(0,jn.jsx)(e.icon,{className:"h-3 w-3"}),e.label]},e.rawLabel))})}):null,$e&&(0,jn.jsx)("div",{className:"px-4 pb-1 max-w-2xl mx-auto w-full",children:(0,jn.jsx)(Io,{search:We,onSelect:e=>{Ce(""),Fe(!1)},onCreateTask:ke?void 0:()=>{ke||(Wt(""),At(!0))},onCreatePoll:()=>{},onMentionOKR:()=>{Ce(""),Fe(!1),z("Show me my current OKR progress and what needs attention.","chat",void 0,void 0,M)},onSetReminder:()=>{Ce(""),Fe(!1),z("What are my upcoming deadlines and reminders?","chat",void 0,void 0,M)},onGenerateSummary:()=>{Ce(""),Fe(!1),z("Summarize my recent activity, key decisions, and important updates.","chat",void 0,void 0,M)},onLogDecision:()=>{qt(""),Vt("From personal assistant conversation"),Ot(!0)}})}),Oe&&(0,jn.jsx)("div",{className:"border-t border-border shrink-0",children:(0,jn.jsx)(fn.Suspense,{fallback:null,children:(0,jn.jsx)(Bl,{projectId:t,settings:H,onClose:()=>Re(!1),onMessagesAdded:G,inline:!0,onPopOut:o?()=>{Re(!1),o(M)}:void 0,threadId:M,onAssistantStream:e=>{ye(e)},onTurnComplete:()=>{ye(null),G()}})})}),(0,jn.jsxs)("div",{className:"px-3 py-2 border-t border-border shrink-0",children:[!ze&&(0,jn.jsxs)("div",{className:"max-w-2xl mx-auto mb-1.5 flex items-center gap-1.5 rounded-md border border-warning/30 bg-warning/10 px-2 py-1 text-[11px] text-warning-strong",children:[(0,jn.jsx)("span",{className:"inline-block h-1.5 w-1.5 rounded-full bg-warning"}),(0,jn.jsx)("span",{children:A("pa.offline_banner")})]}),(0,jn.jsxs)("form",{onSubmit:e=>{e.preventDefault(),nr()},className:"flex gap-1.5 items-center max-w-2xl mx-auto",children:[(0,jn.jsx)(Ye,{type:"button",variant:"ghost",size:"icon",className:He("h-9 w-9 shrink-0 text-primary hover:bg-primary/10",!d&&"hidden md:inline-flex"),onClick:()=>Re(!0),disabled:i||!ze,title:A("pa.voice_mode"),"aria-label":A("pa.voice_mode"),children:(0,jn.jsx)(we,{className:"h-4 w-4"})}),(0,jn.jsx)(Es,{onTranscript:e=>Ce(e),currentValue:Ie,size:"icon",className:"h-9 w-9 shrink-0"}),(0,jn.jsx)(Et,{ref:Pe,value:Ie,onChange:e=>{const t=e.target.value;Ce(t),t.startsWith("/")?(Fe(!0),Ke(t)):(Fe(!1),Ke(""))},placeholder:ze?A(R?"pa.ask_mobile":"pa.ask_desktop",{name:H.display_name}):A("pa.offline_ph"),className:"flex-1 min-w-0",disabled:$||!ze,onKeyDown:e=>{"Escape"===e.key&&Fe(!1)}}),$?(0,jn.jsx)(Ye,{type:"button",size:"icon",variant:"outline",onClick:B,title:A("pa.stop_response"),"aria-label":A("pa.stop_response"),children:(0,jn.jsx)(de,{className:"h-4 w-4"})}):(0,jn.jsx)(Ye,{type:"submit",size:"icon",disabled:!Ie.trim()||!ze,title:A("action.send"),"aria-label":A("action.send"),children:(0,jn.jsx)(w,{className:"h-4 w-4"})})]})]}),(0,jn.jsx)(wo,{open:Tt&&!ke,onOpenChange:At,sourceModule:"COMMUNICATION",sourceContext:Ft,teamMembers:[],showDueDate:!0,onCreateTask:async e=>{if(ke)return;const{tags:t,...r}=e;await Ne({...r,sourceModule:"COMMUNICATION",sourceTitle:"Personal Assistant"})&&(Ae.success(A("pa.task_created")),At(!1))}}),(0,jn.jsx)(ko,{open:Dt,onOpenChange:Ot,projectId:t,initialDecision:Ht,initialContext:zt}),(0,jn.jsx)(so,{open:xt,onOpenChange:bt,preferences:D,onUpdate:O,assistantName:H.display_name,projectId:t,defaultAvatar:H.avatar_emoji,imageOptions:H.avatar_options}),(0,jn.jsx)(rl,{open:Pt,onOpenChange:Lt,projectId:t}),(0,jn.jsx)(Vl,{open:Rt,onClose:()=>Mt(!1),onSave:async e=>{const t=await Se(e);return t&&(Ae.success(A("pa.event_created")),Mt(!1)),t},projectId:t}),(0,jn.jsx)(zo,{pending:X,onClose:ee}),(0,jn.jsx)(al,{pending:te,onConfirm:re,onClose:ae}),(0,jn.jsx)(Ct,{open:me,onOpenChange:pe,children:(0,jn.jsxs)(wt,{children:[(0,jn.jsxs)(It,{children:[(0,jn.jsx)(yt,{children:A("pa.clear_confirm_title")}),(0,jn.jsx)(vt,{children:A("pa.clear_confirm_desc")})]}),(0,jn.jsxs)(kt,{children:[(0,jn.jsx)(St,{children:A("action.cancel")}),(0,jn.jsx)(Nt,{onClick:()=>{V()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:A("pa.clear_conversation")})]})]})}),(0,jn.jsx)(Ct,{open:!!he,onOpenChange:e=>{e||ge(null)},children:(0,jn.jsxs)(wt,{children:[(0,jn.jsxs)(It,{children:[(0,jn.jsx)(yt,{children:A("pa.dataroom_confirm_title")}),(0,jn.jsx)(vt,{children:A("pa.dataroom_confirm_desc")})]}),he&&(0,jn.jsx)("ul",{className:"rounded-md border border-border bg-muted/40 p-2 text-sm text-foreground space-y-0.5 max-h-40 overflow-y-auto",children:he.map((e,t)=>(0,jn.jsxs)("li",{className:"truncate",children:["ð ",e.name," ",(0,jn.jsxs)("span",{className:"text-xs text-muted-foreground",children:["(",Math.max(1,Math.round(e.size/1024))," KB)"]})]},`${e.name}-${t}`))}),(0,jn.jsxs)("div",{className:"flex items-start gap-3 rounded-md border border-border p-3",children:[(0,jn.jsx)(sa,{id:"pa-drop-share-investors",checked:xe,onCheckedChange:_e}),(0,jn.jsxs)("div",{className:"space-y-0.5",children:[(0,jn.jsx)(na,{htmlFor:"pa-drop-share-investors",className:"text-sm font-medium",children:A("pa.dataroom_share_investors")}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground",children:A("pa.dataroom_share_hint")})]})]}),(0,jn.jsxs)(kt,{children:[(0,jn.jsx)(St,{children:A("action.cancel")}),(0,jn.jsx)(Nt,{onClick:()=>{const e=he,r=xe;ge(null),e?.length&&(async(e,r)=>{if(t)for(const s of e)try{await As(t,s,"chat_upload",{sharedWithInvestors:r})?(Ae.success(A(r?"pa.saved_dataroom_investors":"pa.saved_dataroom_team",{name:s.name})),Q(A(r?"pa.file_saved_note_investors":"pa.file_saved_note_team",{name:s.name,size:Math.round(s.size/1024)}))):Ae.error(A("pa.save_dataroom_failed",{name:s.name}))}catch(a){Ge.error("Chat upload failed",a),Ae.error(A("pa.upload_failed",{name:s.name}))}})(e,r)},children:A("pa.dataroom_save")})]})]})}),(0,jn.jsx)(nl,{open:Ut,onOpenChange:$t,assistantName:H.display_name,disabled:$,onPick:e=>{$t(!1),z(e,"chat",void 0,void 0,M)}})]})});function Xl(e,t){if(0===e.length)return t;const r=new Map(e.map(e=>[e.id,e]));let a=e.length===t.length;const s=t.map((t,s)=>{const n=r.get(t.id),i=!!n&&(n.updatedAt===t.updatedAt||!!n.updatedAt&&!!t.updatedAt&&n.updatedAt>t.updatedAt),o=n&&i?n:t;return o!==e[s]&&(a=!1),o});return a?e:s}var ec=(e,t)=>{const r=e.updatedAt||"",a=t.updatedAt||"";return r<a?1:r>a?-1:0};function tc(e,t,r={}){const a=!!r.readOnly,{user:s}=$t(),[n,i]=(0,fn.useState)([]),[o,l]=(0,fn.useState)([]),[c,d]=(0,fn.useState)([]),[u,m]=(0,fn.useState)([]),[p,h]=(0,fn.useState)(!0),[f,g]=(0,fn.useState)(null),x=(0,fn.useRef)(0),_=(0,fn.useRef)(0),b=(0,fn.useRef)(0),j=(0,fn.useRef)(0),v=(0,fn.useRef)(0),y=(0,fn.useRef)(new Set),w=(0,fn.useRef)(null),N=(0,fn.useRef)(0),k=(0,fn.useRef)(new Map),S=(0,fn.useRef)(null),I=(0,fn.useCallback)(async()=>
2{if(!s||!e)return;const r=`${e}:${t??""}`,n=++v.current,o=S.current!==r;x.current++,_.current++,b.current++,j.current++;try{o&&h(!0),g(null);const s=t&&!a?Ks(e,t).then(r=>r.length>0?r:Hs(e,t)):Hs(e,t),[c,u,p,f]=await Promise.all([s,Qs(e,{pipelineId:t}),Js(e,{pipelineId:t}),Fs(e,{pipelineId:t})]);if(n!==v.current)return;i(e=>o?c:Xl(e,c)),l(e=>o?u:Xl(e,u)),d(e=>o?p:Xl(e,p)),m(e=>o?f:Xl(e,f)),S.current=r}catch(c){Ge.error("Error loading CRM data:",c),n===v.current&&g("Failed to load CRM data")}finally{n===v.current&&h(!1)}},[s,e,t,a]);(0,fn.useEffect)(()=>{I()},[I]);const C=(0,fn.useRef)(I);(0,fn.useEffect)(()=>{C.current=I},[I]),(0,fn.useEffect)(()=>{const e=()=>{C.current()};return window.addEventListener("crm-updated-externally",e),()=>window.removeEventListener("crm-updated-externally",e)},[]),(0,fn.useEffect)(()=>{x.current++,_.current++,b.current++,j.current++,v.current++,y.current.clear()},[e,t]);const E=(0,fn.useCallback)(()=>{if(!e)return;const r=++x.current;Fs(e,{pipelineId:t}).then(e=>{r===x.current&&m(t=>Xl(t,e))})},[e,t]),T=(0,fn.useCallback)(async()=>{w.current=null;const r=[...y.current];if(y.current.clear(),!e||0===r.length)return;if(r.length>200)return void E();const a=x.current,s=++N.current;r.forEach(e=>k.current.set(e,s));const{deals:n,ok:i}=await Bs(r);if(!i)return void E();if(a!==x.current)return;const o=new Set(r.filter(e=>k.current.get(e)===s));if(o.forEach(e=>k.current.delete(e)),0===o.size)return;const l=new Map(n.filter(e=>o.has(e.id)).map(e=>[e.id,e])),c=e=>!(e.deletedAt||t&&e.pipelineId!==t);m(e=>{let t=!1;const r=[];for(const a of e){if(!o.has(a.id)){r.push(a);continue}const e=l.get(a.id);l.delete(a.id),e&&c(e)?e.updatedAt!==a.updatedAt?(r.push(e),t=!0):r.push(a):t=!0}for(const a of l.values())c(a)&&(r.push(a),t=!0);return t?r.sort(ec):e})},[e,t,E]),A=(0,fn.useRef)(T);(0,fn.useEffect)(()=>{A.current=T},[T]),(0,fn.useEffect)(()=>()=>{w.current&&clearTimeout(w.current)},[]),Qt(e,"crm_deals",{onChange:e=>{const t=e.new&&Object.keys(e.new).length>0?e.new:e.old,r="string"==typeof t?.id?t.id:null;r?(y.current.add(r),w.current||(w.current=setTimeout(()=>{A.current()},150))):E()}},[e,t]),Qt(e,"crm_contacts",{onChange:()=>{const r=++_.current;Js(e,{pipelineId:t}).then(e=>{r===_.current&&d(t=>Xl(t,e))})}},[e,t]),Qt(e,"crm_organizations",{onChange:()=>{const r=++b.current;Qs(e,{pipelineId:t}).then(e=>{r===b.current&&l(t=>Xl(t,e))})}},[e,t]),Qt(e,"crm_pipeline_stages",{onChange:()=>{const r=++j.current;Hs(e,t).then(e=>{r===j.current&&i(t=>Xl(t,e))})}},[e,t]);const D=(0,fn.useCallback)(async(e,t)=>{let r,a=-1;d(t=>{const s=t.findIndex(t=>t.id===e);return-1===s?t:(r=t[s],a=s,t.slice(0,s).concat(t.slice(s+1)))});const s=await Ws(e,t);if(!s&&r){const t=r,s=a;d(r=>{if(r.some(t=>t.id===e))return r;const a=Math.min(s,r.length);return[...r.slice(0,a),t,...r.slice(a)]})}return s},[]),O=(0,fn.useCallback)(async(e,t)=>{let r,a=-1;m(t=>{const s=t.findIndex(t=>t.id===e);return-1===s?t:(r=t[s],a=s,t.slice(0,s).concat(t.slice(s+1)))});const s=await Vs(e,t);if(!s&&r){const t=r,s=a;m(r=>{if(r.some(t=>t.id===e))return r;const a=Math.min(s,r.length);return[...r.slice(0,a),t,...r.slice(a)]})}return s},[]),R=(0,fn.useCallback)(async(e,t)=>{let r,a=-1;l(t=>{const s=t.findIndex(t=>t.id===e);return-1===s?t:(r=t[s],a=s,t.slice(0,s).concat(t.slice(s+1)))});const s=await Ys(e,t);if(!s&&r){const t=r,s=a;l(r=>{if(r.some(t=>t.id===e))return r;const a=Math.min(s,r.length);return[...r.slice(0,a),t,...r.slice(a)]})}return s},[]),M=(0,fn.useCallback)(async(e,t)=>{let r;d(a=>a.map(a=>a.id!==e?a:(r=a,{...a,...t})));const a=await Ps(e,t);if(!a&&r){const t=r;d(r=>r.map(r=>r.id===e?t:r))}return a},[]),P=(0,fn.useCallback)(async(e,t)=>{let r;m(a=>a.map(a=>a.id!==e?a:(r=a,{...a,...t})));const a=await zs(e,t);if(!a&&r){const t=r;m(r=>r.map(r=>r.id===e?t:r))}return a},[]),L=(0,fn.useCallback)(async(e,t)=>{let r;l(a=>a.map(a=>a.id!==e?a:(r=a,{...a,...t})));const a=await Ms(e,t);if(!a&&r){const t=r;l(r=>r.map(r=>r.id===e?t:r))}return a},[]),U=(0,fn.useCallback)(async(e,t,r)=>{let a;m(r=>r.map(r=>r.id!==e?r:(a=r,{...r,stage:t})));const s=await Rs(e,t,r);if(!s&&a){const t=a;m(r=>r.map(r=>r.id===e?t:r))}return s},[]);return{stages:n,organizations:o,contacts:c,deals:u,loading:p,error:f,refresh:I,createContact:qs,updateContact:M,deleteContact:D,createOrganization:Gs,updateOrganization:L,deleteOrganization:R,createDeal:$s,updateDeal:P,updateDealStage:U,deleteDeal:O,logActivity:Ls}}function rc(e,t,r=100){const[a,s]=(0,fn.useState)([]),[n,i]=(0,fn.useState)(!0),o=(0,fn.useCallback)(async()=>
2{if(e)try{i(!0);const a=await Us(e,t,r);s(a)}finally{i(!1)}},[e,t.dealId,t.contactId,t.organizationId,r]);return(0,fn.useEffect)(()=>{o()},[o]),Qt(e,"crm_activities",{onChange:()=>{o()}},[e,t.dealId,t.contactId,t.organizationId]),{activities:a,loading:n,refresh:o}}var ac=["Won","Lost","Passed","Rejected","Cancelled"];var sc=new Set(Object.values(jt)),nc={finance:jt.FINANCE_DASHBOARD,financedashboard:jt.FINANCE_DASHBOARD,tasks:jt.TASKS,okrs:jt.OKRS,notes:jt.NOTES,chat:jt.COMMUNICATION,communication:jt.COMMUNICATION,mentor:jt.MENTOR,whiteboard:jt.WHITEBOARD,advertising:jt.GROWTH,growth:jt.GROWTH,investors:jt.INVESTOR_PIPELINE,investorpipeline:jt.INVESTOR_PIPELINE,crm:jt.CRM,sales:jt.CRM,deals:jt.CRM,mail:jt.MAIL,inbox:jt.MAIL,drive:jt.DRIVE,storage:jt.DRIVE,files:jt.DRIVE,risk:jt.RISK,mentorcoach:jt.MENTOR,"competitor-war-room":jt.COMPETITOR_WAR_ROOM,ideation:jt.IDEATION,"market-research":jt.MARKET_RESEARCH,"customer-discovery":jt.CUSTOMER_DISCOVERY,strategy:jt.STRATEGY,product:jt.PRODUCT,marketing:jt.MARKETING,financials:jt.FINANCIALS,legal:jt.LEGAL,team:jt.TEAM,"pitch-deck":jt.PITCH_DECK,fundraising:jt.FUNDRAISING,calendar:jt.CALENDAR,meetings:jt.MEETINGS,hr:jt.HR,github:jt.GITHUB,pricing:jt.PRICING,dashboard:jt.DASHBOARD,today:jt.DASHBOARD};function ic(e){if("string"!=typeof e||!e.trim())return null;const t=e.trim();if(sc.has(t))return t;const r=function(e){return e.trim().replace(/[_\s]+/g,"-").toLowerCase()}(t);return nc[r]||nc[r.replace(/-/g,"")]||null}function oc(e){const t=(0,fn.useCallback)((t,r)=>{const a=ic(t)||r||null;return a&&e(a),a},[e]),r=(0,fn.useCallback)((e,t)=>function(e,t,r){try{const a=e.getItem(`1tab_lastVisit_${t}`);if(!a)return null;const s=JSON.parse(a),n=ic(s.module);return"string"==typeof s.projectId&&r.has(s.projectId)&&"string"==typeof s.projectName&&n?{projectId:s.projectId,projectName:s.projectName,module:n}:null}catch{return null}}(localStorage,e,t),[]);return{navigateToModule:t,persistLastVisit:(0,fn.useCallback)((e,t)=>{!function(e,t,r){e.setItem(`1tab_lastVisit_${t}`,JSON.stringify(r))}(localStorage,e,t)},[]),readLastVisit:r}}var lc=["task","note","openNoteId","okr","kr","channel","message","meeting","settings","projectId","restore"],cc=(e,t)=>{const r=e.get(t)?.trim();return r||null};function dc(e){const t=new URLSearchParams(e);return{projectId:cc(t,"project")??cc(t,"projectId"),module:ic(cc(t,"module")),taskId:cc(t,"task"),noteId:cc(t,"note")??cc(t,"openNoteId"),okrId:cc(t,"okr"),channel:cc(t,"channel"),messageId:cc(t,"message"),meetingId:cc(t,"meeting"),settings:cc(t,"settings"),skipRestore:"0"===t.get("restore")}}function uc(e){return e.module?e.module:e.taskId?jt.TASKS:e.noteId?jt.NOTES:e.okrId?jt.OKRS:e.channel||e.messageId?jt.COMMUNICATION:e.meetingId?jt.MEETINGS:null}function mc(e,t,r){if(function(e,t,r){const a=new URLSearchParams(e);return!lc.some(e=>a.has(e))&&(t?a.get("project")===t&&a.get("module")===r:!a.has("project")&&!a.has("module"))}(e,t,r))return"none";const a=new URLSearchParams(e);if(lc.some(e=>a.has(e)))return"replace";const s=a.get("project");return t&&s===t?a.has("module")&&ic(a.get("module"))!==r?"push":"replace":t||s?"push":"replace"}function pc(e,t,r){const a=new URLSearchParams(e);for(const n of lc)a.delete(n);t?(a.set("project",t),a.set("module",r)):(a.delete("project"),a.delete("module"));const s=a.toString();return s?`?${s}`:""}var hc={notifications:"notifications",notification:"notifications",email:"notifications",emails:"notifications",billing:"subscription",subscription:"subscription",plan:"subscription",security:"security",profile:"profile",account:"profile",referrals:"referrals","okr-reminders":"okr-reminders",hr:"hr","ai-usage":"ai-usage",usage:"ai-usage",credits:"ai-usage"};function fc({children:e}){return(0,jn.jsx)("div",{className:"w-full",children:e})}function gc({module:e}){return(0,fn.useEffect)(()=>{wa.ready()},[e]),null}function xc({activeModule:e,renderers:t,persistentRenderers:r=[],wrapActiveModule:a,blocked:s,blockedReason:n,templateEnabled:i,onBack:o}){const l=t[e],[c,d]=(0,fn.useState)(()=>new Set),u=r.filter(e=>e.visible&&!1!==e.enabled&&!c.has(e.module));u.length>0&&d(e=>{const t=new Set(e);
2return u.forEach(e=>t.add(e.module)),t});const m=r.filter(e=>!1!==e.enabled&&(e.visible||c.has(e.module)));return(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(Nr,{}),children:s?(0,jn.jsx)(ki,{module:e,reason:n,onBack:o}):(0,jn.jsxs)(yr,{enabled:i,children:[a?a(l?.()??null,e):l?.()??null,m.map(e=>(0,jn.jsx)("div",{"data-persistent-module":e.module,style:{display:e.visible?void 0:"none"},"aria-hidden":!e.visible||void 0,children:e.render()},e.module)),(0,jn.jsx)(gc,{module:e})]})})}var _c={version:1,favorites:[],recent:[]},bc=e=>"string"==typeof e&&"execution"===Gt(e)?.phase,jc=(e,t)=>Array.isArray(e)?[...new Set(e.filter(bc))].slice(0,t):[],vc=(e,t)=>bc(t)?[t,...e.filter(e=>e!==t)].slice(0,5):[...e],yc=(e,t)=>bc(t)?e.includes(t)?e.filter(e=>e!==t):[t,...e].slice(0,6):[...e],wc=e=>`1tab.module-navigation.v1:${e}`,Nc=e=>e?(e=>{if(!e)return{..._c};try{const t=JSON.parse(e);return 1!==t.version?{..._c}:{version:1,favorites:jc(t.favorites,6),recent:jc(t.recent,5)}}catch{return{..._c}}})(zr(wc(e))):{..._c},kc=({theme:e,onToggleTheme:t,onLogout:r,showExtras:a=!1,presenceCount:s=0,onOpenWallet:n,onOpenNews:i})=>{const{user:l}=$t(),{isAdmin:c}=Yt(),d=Ve(),[u,m]=(0,fn.useState)("");(0,fn.useEffect)(()=>{l&&m(l.user_metadata?.display_name||l.email?.split("@")[0]||"User")},[l]);return(0,jn.jsxs)(_a,{children:[(0,jn.jsx)(fa,{asChild:!0,children:(0,jn.jsx)("button",{className:"flex items-center gap-2 p-1.5 rounded-full hover:bg-muted transition-colors focus:outline-none focus:ring-2 focus:ring-primary/50",children:(0,jn.jsxs)(ys,{className:"w-8 h-8 border-2 border-primary/30",children:[(0,jn.jsx)(vs,{src:l?ws(l.id):void 0}),(0,jn.jsx)(js,{className:"bg-gradient-to-br from-primary to-primary/70 text-primary-foreground text-xs font-bold",children:(p=u,p.split(" ").map(e=>e[0]).join("").toUpperCase().slice(0,2))})]})})}),(0,jn.jsxs)(ga,{align:"end",className:"w-56",children:[(0,jn.jsx)(ha,{className:"font-normal",children:(0,jn.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,jn.jsx)("p",{className:"text-sm font-medium leading-none",children:u}),l?.email&&(0,jn.jsx)("p",{className:"text-xs leading-none text-muted-foreground",children:l.email})]})}),(0,jn.jsx)(pa,{}),(0,jn.jsxs)(xa,{onClick:()=>d("/profile"),children:[(0,jn.jsx)(Pe,{className:"mr-2 h-4 w-4"}),"My Profile"]}),(0,jn.jsxs)(xa,{onClick:()=>d("/me"),children:[(0,jn.jsx)(T,{className:"mr-2 h-4 w-4"}),"My HR"]}),c&&(0,jn.jsxs)(xa,{onClick:()=>d("/admin"),children:[(0,jn.jsx)(P,{className:"mr-2 h-4 w-4"}),"Admin Dashboard"]}),a&&(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsxs)(xa,{onClick:n,children:[(0,jn.jsx)(Se,{className:"mr-2 h-4 w-4"}),"Wallet"]}),s>0&&(0,jn.jsxs)(xa,{className:"cursor-default",children:[(0,jn.jsx)(G,{className:"mr-2 h-4 w-4"}),(0,jn.jsxs)("span",{children:[s," online"]})]}),(0,jn.jsxs)(xa,{onClick:i,children:[(0,jn.jsx)(o,{className:"mr-2 h-4 w-4"}),"News & Updates"]}),(0,jn.jsxs)(xa,{onClick:()=>window.open("/developers","_blank"),children:[(0,jn.jsx)(oe,{className:"mr-2 h-4 w-4"}),"Developer API"]})]}),(0,jn.jsx)(pa,{}),(0,jn.jsxs)(xa,{onClick:t,children:["dark"===e?(0,jn.jsx)(R,{className:"mr-2 h-4 w-4"}):(0,jn.jsx)(fe,{className:"mr-2 h-4 w-4"}),"dark"===e?"Light Mode":"Dark Mode"]}),(0,jn.jsx)(pa,{}),(0,jn.jsxs)(xa,{onClick:r,className:"text-destructive focus:text-destructive",children:[(0,jn.jsx)(re,{className:"mr-2 h-4 w-4"}),"Log Out"]})]})]});var p};function Sc({projectId:e,onLaunchVoice:t,voiceActive:r,globalVoiceActive:a,activeModule:n,isNewProject:i}){const{t:o}=at(),{user:l}=$t(),{unreadCount:c}=lo(e),[d,u]=(0,fn.useState)(!1),[m,h]=(0,fn.useState)(!1),g=(0,fn.useRef)(!1),[x,_]=(0,fn.useState)(!1),[b,j]=(0,fn.useState)(!1),[y,w]=(0,fn.useState)(""),[N,I]=(0,fn.useState)(!1),[C,E]=(0,fn.useState)(0),[T,A]=(0,fn.useState)(!1),D=(0,fn.useRef)(null),[O,R]=(0,fn.useState)(null),M=(0,fn.useCallback)(e=>{R(t=>t?.id===e?null:t)},[]);(0,fn.useEffect)(()=>{if(!i||g.current||!l?.id)return;const t=`1tab_assistant_opened_${e}_${l.id}`;if(localStorage.getItem(t))return;g.current=!0;const r=setTimeout(()=>{localStorage.setItem(t,"1"),u(!0),h(!1)},1800);return()=>clearTimeout(r)},[i,e,l?.id]);const P=(0,fn.useRef)(t);return P.current=t,(0,fn.useEffect)(()=>{const e=()=>{u(!0),h(!1)},t=t=>{e();const r=t.detail?.prompt,a="string"==typeof r?r.trim().slice(0,4e3):"";a&&R({id:crypto.randomUUID(),text:a})},r=()=>{u(!1),P.current()};return window.addEventListener(cr,t),window.addEventListener("pa:open-chat",e),window.addEventListener("pa:open-voice",r),
2()=>{window.removeEventListener(cr,t),window.removeEventListener("pa:open-chat",e),window.removeEventListener("pa:open-voice",r)}},[]),(0,jn.jsxs)(jn.Fragment,{children:[d&&m&&(0,jn.jsxs)(Er.button,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},onClick:()=>h(!1),className:"fixed right-6 z-[900] flex items-center gap-2 rounded-full bg-ai text-ai-foreground px-4 py-2 shadow-xl text-sm font-medium hover:bg-ai/90 transition-colors bottom-[calc(var(--mobile-bottom-nav-h)_+_1rem)] lg:bottom-20",children:[(0,jn.jsxs)("span",{className:"relative flex items-center",children:[(0,jn.jsx)(Kr,{className:"w-4 h-4 text-ai-foreground"}),c>0&&(0,jn.jsx)("span",{className:"absolute -top-2 -right-2 min-w-[16px] h-4 px-1 rounded-full bg-destructive text-destructive-foreground text-[9px] font-bold flex items-center justify-center border border-background",children:c>9?"9+":c})]}),(0,jn.jsx)("span",{children:"Assad"}),(0,jn.jsx)(v,{className:"w-3.5 h-3.5"})]}),(0,jn.jsx)(Ar,{children:d&&!m&&(0,jn.jsxs)(Er.div,{initial:{opacity:0,y:40,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:40,scale:.95},transition:{duration:.25},className:"fixed bottom-6 right-6 z-[900] w-[400px] h-[520px] max-w-[calc(100vw-2rem)] max-h-[calc(100vh-4rem)] rounded-xl border border-border bg-background shadow-2xl flex flex-col overflow-hidden",children:[(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border bg-muted/50",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,jn.jsx)("div",{className:"w-6 h-6 rounded-full bg-gradient-to-br from-ai to-ai-glow flex items-center justify-center",children:(0,jn.jsx)(Kr,{className:"w-3.5 h-3.5 text-ai-foreground"})}),(0,jn.jsx)("span",{className:"text-sm font-semibold text-foreground truncate",children:"Assad"})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-0.5",children:[(0,jn.jsx)("button",{onClick:()=>_(!0),disabled:a,className:"p-1.5 rounded-md hover:bg-muted transition-colors text-primary disabled:opacity-50 disabled:cursor-not-allowed",title:o("pa.start_voice"),"aria-label":o("pa.start_voice"),children:(0,jn.jsx)(we,{className:"w-4 h-4"})}),(0,jn.jsxs)(_a,{children:[(0,jn.jsx)(fa,{asChild:!0,children:(0,jn.jsx)("button",{className:He("p-1.5 rounded-md hover:bg-muted transition-colors",b||N?"text-primary":"text-muted-foreground"),title:o("pa.more_options"),"aria-label":o("pa.more_options"),children:(0,jn.jsx)(p,{className:"w-4 h-4"})})}),(0,jn.jsxs)(ga,{align:"end",className:"w-48",children:[(0,jn.jsxs)(xa,{onClick:()=>{const e=!b;j(e),e||w("")},children:[(0,jn.jsx)(k,{className:"w-4 h-4 mr-2"}),o(b?"pa.hide_search":"pa.search_conversation")]}),C>0&&(0,jn.jsxs)(xa,{onClick:()=>I(!N),children:[(0,jn.jsx)(ue,{className:"w-4 h-4 mr-2"}),N?o("pa.show_all_messages"):o("pa.show_pinned_only",{count:C})]}),(0,jn.jsxs)(xa,{onClick:()=>A(!0),children:[(0,jn.jsx)(s,{className:"w-4 h-4 mr-2"}),o("pa.assistant_settings")]}),(0,jn.jsx)(pa,{}),(0,jn.jsxs)(xa,{onClick:()=>D.current?.clearHistory(),className:"text-destructive focus:text-destructive",children:[(0,jn.jsx)(f,{className:"w-4 h-4 mr-2"}),o("pa.clear_conversation")]})]})]}),(0,jn.jsx)("button",{onClick:()=>h(!0),className:"p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground",title:o("action.minimize"),"aria-label":o("action.minimize"),children:(0,jn.jsx)(S,{className:"w-4 h-4"})}),(0,jn.jsx)("button",{onClick:()=>u(!1),className:"p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground",title:o("action.close"),"aria-label":o("action.close"),children:(0,jn.jsx)(J,{className:"w-4 h-4"})})]})]}),(0,jn.jsx)("div",{className:"flex-1 overflow-hidden",children:(0,jn.jsx)(Je,{module:"Assad",projectId:e,children:(0,jn.jsx)(Zl,{ref:D,projectId:e,globalVoiceActive:a,onPopOutVoice:t,activeModule:n,isNewProject:i,hideHeader:!0,voiceMode:x,onVoiceModeChange:_,showSearch:b,onShowSearchChange:j,searchQuery:y,onSearchQueryChange:w,showPinnedOnly:N,onShowPinnedOnlyChange:I,onPinnedCountChange:E,showPreferences:T,onShowPreferencesChange:A,pendingPrompt:O,onPendingPromptConsumed:M})})})]})})]})}var Ic=it(()=>qe(()=>import("./ModuleTransitionCoach-DjsuQ0tH.js").then(e=>({default:e.ModuleTransitionCoach})),__vite__mapDeps([49,1,2,3,8,9,10,11,5,6,7,4,12,27,50,23,15,51,36,35,14,37,38,16,17,18,19,20,21,39,40,13,25,41,42]))),Cc=it(()=>qe(()=>import("./CoachFeedbackFloatingButton-DA-jKGYp.js").then(e=>({default:e.CoachFeedbackFloatingButton})),__vite__mapDeps([52,1,2,3,11,5,6,7,4,10,9,8,12,27,50,23]))),Ec=it(()=>qe(()=>import("./onboarding-Byk_kXSF.js").then(e=>({default:e.OnboardingWizard})),__vite__mapDeps([53,1,2,3,4,5,6,7,11,10,9,8,12,27,54,51,55]))),Tc=it(()=>qe(()=>import("./AssadVoiceMode-CT4anZCz.js").then(e=>({default:e.AssadVoiceMode})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47]))),Ac=it(()=>qe(()=>import("./PortfolioOnboardingDialog-DIQVtTuK.js").then(e=>({default:e.PortfolioOnboardingDialog})),__vite__mapDeps([56,1,2,3,57,5,6,7,4,11,10,9,8,12]))),Dc=it(()=>qe(()=>import("./templates-B8_eOZ_i.js").then(e=>({default:e.CrossModuleTemplateDialog})),__vite__mapDeps([58,1,2,3,4,5,6,7,8,9,10,11,12,13,14,27,50,54,15,16,17,18,19,20,21,51,37,55]))),Oc=it(()=>qe(()=>import("./KeyboardShortcutHelp-CeElW83u.js").then(e=>({default:e.KeyboardShortcutHelp})),__vite__mapDeps([59,1,2,3,27,5,6,7,4,23,26,8,9,10,11,12,14,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32]))),Rc=it(()=>qe(()=>import("./PhaseTransitionGuide-oc-e1VAh.js").then(e=>({default:e.PhaseTransitionGuide})),__vite__mapDeps([60,1,2,3,11,5,6,7,4,10,9,8,12,50,57]))),Mc=it(()=>qe(()=>import("./CalendarReminderRunner-C1wV1H7M.js").then(e=>e.n).then(e=>({default:e.CalendarReminderRunner})),__vite__mapDeps([61,1,2,3,8,9,10,13,11,5,6,7,4,12,14,15,16,17,18,19,20,21]))),Pc=fn.memo(function(e){const t=Kt();(0,fn.useEffect)(()=>nr(e=>Zt(e)&&e.shiftKey&&!e.altKey&&wr(e,"k")&&!e.target?.closest?.('[data-no-global-shortcuts="true"]'),e=>{e.preventDefault(),window.dispatchEvent(new CustomEvent("pa:open-voice"))}),[]);const{currentProject:r,activeModule:a,setActiveModule:s,showExecutionWelcome:n,setShowExecutionWelcome:i,calculatePlanningCompletion:o,planningNavItems:l,isModuleCompleted:c,pendingTransition:d,showTransitionCoach:u,setShowTransitionCoach:m,setPendingTransition:p,handleTransitionContinue:h,handleTransitionGoBack:f,handleDisableTransitionCoach:g,lastCoachAnalysis:x,lastAnalyzedModule:_,setLastCoachAnalysis:b,setLastAnalyzedModule:j,showOnboardingWizard:v,setShowOnboardingWizard:y,handleOnboardingComplete:w,showPortfolioOnboarding:N,setShowPortfolioOnboarding:k,showCrossModuleTemplateDialog:S,setShowCrossModuleTemplateDialog:I,directUpdateProject:C,globalVoiceActive:E,globalVoiceProjectId:T,globalVoiceThreadId:A,globalVoiceSettings:D,handlePopOutVoice:O,handleStopGlobalVoice:R}=e;return(0,jn.jsxs)(fn.Suspense,{fallback:null,children:[(0,jn.jsx)(Rc,{open:n,onClose:()=>i(!1),planningCompletion:o(r),planningModules:l,isModuleCompleted:e=>
2c(e,r),onReviewModule:e=>s(e)}),d&&(0,jn.jsx)(Ic,{isOpen:u,onClose:()=>{m(!1),p(null)},fromModule:d.from,toModule:d.to,state:r,onContinue:h,onGoBack:f,onDisableCoach:g,onAnalysisComplete:(e,t)=>{b(e),j(t)}}),!u&&!t&&(0,jn.jsx)(Cc,{lastAnalysis:x,lastAnalyzedModule:_,onDismiss:()=>{b(null),j(null)}}),(0,jn.jsx)(Ec,{open:v,onClose:()=>y(!1),onComplete:w}),(0,jn.jsx)(Ac,{open:N,onClose:()=>k(!1)}),(0,jn.jsx)(Dc,{open:S,onOpenChange:I,projectId:r.id,currentBoards:r.boards||[],currentTasks:r.tasks||[],currentOKRs:r.okrs?.objectives||[],onUpdateProject:async e=>{if(!(await C(e)))throw new Error("The template could not be saved. Please try again.")},onNavigateToTasks:()=>s(jt.TASKS),onNavigateToNotes:()=>s(jt.NOTES)}),(0,jn.jsx)(Oc,{activeModule:a}),(0,jn.jsx)(Mc,{}),(0,jn.jsx)(Sc,{projectId:r.id,onLaunchVoice:e=>O(r.id,{display_name:"Assad",avatar_emoji:"ð¤"},e??null),voiceActive:E,globalVoiceActive:E,onStopGlobalVoice:R,activeModule:a,isNewProject:!1}),E&&T&&(0,jn.jsx)(Tc,{projectId:T,settings:D,onClose:R,floating:!0,activeModule:a,threadId:A})]})}),Lc={[jt.IDEATION]:"ideation",[jt.CUSTOMER_DISCOVERY]:"customerDiscovery",[jt.MARKET_RESEARCH]:"marketResearch",[jt.STRATEGY]:"strategy",[jt.PRODUCT]:"product",[jt.MARKETING]:"marketing",[jt.FINANCIALS]:"financials",[jt.LEGAL]:"legal",[jt.TEAM]:"team",[jt.PITCH_DECK]:"pitchDeck",[jt.FUNDRAISING]:"fundraising",[jt.WEBSITE]:"website"},Uc={okrs:jt.OKRS,tasks:jt.TASKS,growth:jt.GROWTH,financeDashboard:jt.FINANCE_DASHBOARD,investorPipeline:jt.INVESTOR_PIPELINE,risk:jt.RISK,mentor:jt.MENTOR},$c=Object.fromEntries(Object.entries(Uc).map(([e,t])=>[e,qt(t)])),Fc=()=>"undefined"!=typeof document&&"hidden"===document.visibilityState?"away":"online",Wc=["#4F46E5","#7C3AED","#EC4899","#EF4444","#F97316","#84CC16","#06B6D4","#3B82F6","#8B5CF6","#14B8A6"],Kc=e=>{let t=0;for(let r=0;r<e.length;r++)t=e.charCodeAt(r)+((t<<5)-t);return Wc[Math.abs(t)%Wc.length]},Hc=(e,t)=>{const[r,a]=(0,fn.useState)([]),[s,n]=(0,fn.useState)(null),i=(0,fn.useRef)(null),o=(0,fn.useRef)(null),l=(0,fn.useRef)(t),c=(0,fn.useRef)(t);c.current=t;const d=(0,fn.useRef)(Fc());(0,fn.useEffect)(()=>{if(a([]),n(null),!e)return;let t=!1,r=null;return(async()=>{const{data:{user:s}}=await Lt.auth.getUser();if(!s||t)return;if(n(s.id),!o.current||o.current.userId!==s.id){const{data:e}=await Lt.from("profiles").select("display_name").eq("user_id",s.id).maybeSingle();if(t)return;o.current={userId:s.id,name:e?.display_name||s.email?.split("@")[0]||"Anonymous",color:Kc(s.id)}}const u=`presence:${e}`;if(await Is(u),t)return;const m=Lt.channel(u,{config:{private:!0}});m.on("presence",{event:"sync"},()=>{if(t)return;const r=m.presenceState(),n=new Map,i=new Map;i.set(s.id,d.current),Object.values(r).forEach(e=>{e.forEach(e=>{if(!e.user_id)return;const t="away"===e.status?"away":"online";if(e.user_id!==s.id&&"online"!==i.get(e.user_id)&&i.set(e.user_id,t),e.user_id!==s.id){const r=n.get(e.user_id);if(r&&r.lastSeen>=e.online_at)return;n.set(e.user_id,{id:e.user_id,name:e.name,module:e.module,section:e.section,color:e.color,lastSeen:e.online_at,isTyping:e.isTyping,typingSection:e.typingSection,editingItemId:e.editingItemId,editingItemType:e.editingItemType,editingItemTitle:e.editingItemTitle,status:t})}})}),function(e,t){_o={projectId:e,users:t},bo.forEach(e=>e())}(e,i),a(Array.from(n.values()))}).on("presence",{event:"join"},({newPresences:e})=>{}).on("presence",{event:"leave"},({leftPresences:e})=>{}).subscribe(async(e,a)=>{if(!t&&"CHANNEL_ERROR"===e&&Cs(a))return i.current===m&&(i.current=null),r===m&&(r=null),void Lt.removeChannel(m);!t&&"SUBSCRIBED"===e&&o.current&&(l.current=c.current,await m.track({user_id:s.id,name:o.current.name,module:c.current,color:o.current.color,online_at:(new Date).toISOString(),isTyping:!1,typingSection:null,status:d.current}))}),r=m,i.current=m})(),()=>{t=!0,r&&Lt.removeChannel(r),i.current===r&&(i.current=null),function(e){_o.projectId===e&&(_o=xo,bo.forEach(e=>e()))}(e)}},[e]),(0,fn.useEffect)(()=>{if(!e||"undefined"==typeof document)return;const t=()=>{const e=Fc();if(e===d.current)return;d.current=e;const t=o.current,r=i.current;t&&r&&r.track({user_id:t.userId,name:t.name,module:l.current,color:t.color,online_at:(new Date).toISOString(),isTyping:!1,typingSection:null,status:e})};return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[e]),(0,fn.useEffect)(()=>
2{if(!e||!o.current)return;if(l.current===t)return;l.current=t;(async()=>{const e=o.current,r=i.current;e&&r&&await r.track({user_id:e.userId,name:e.name,module:t,color:e.color,online_at:(new Date).toISOString(),isTyping:!1,typingSection:null,status:d.current})})()},[t,e]);const u=(0,fn.useCallback)(async(e,r)=>{const a=i.current;if(!a||!s||!o.current)return;const n=o.current;await a.track({user_id:n.userId,name:n.name,module:t,section:r,color:n.color,online_at:(new Date).toISOString(),isTyping:e,typingSection:e?r:null,status:d.current})},[s,t]),m=(0,fn.useCallback)(async(e,r,a)=>{const n=i.current;if(!n||!s||!o.current)return;const l=o.current;await n.track({user_id:l.userId,name:l.name,module:t,color:l.color,online_at:(new Date).toISOString(),isTyping:!1,typingSection:null,editingItemId:e||null,editingItemType:r||null,editingItemTitle:a||null,status:d.current})},[s,t]);return{presenceUsers:r,typingUsers:r.filter(e=>e.isTyping&&e.module===t),setTyping:u,updateEditingItem:m,getUsersEditingItem:(0,fn.useCallback)(e=>r.filter(t=>t.editingItemId===e),[r])}};function qc(e,t){const r=new globalThis.Map(e.map(e=>[e.id,e]));return t.forEach(e=>{e?.id&&r.set(e.id,e)}),Array.from(r.values())}function zc({onClick:e,showDropdown:t=!0,className:r}){const{balance:a,loading:s,error:n,activeWallet:i,refreshWallet:o}=Wr();return(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",onClick:e,className:He("gap-2 px-3 py-1.5 h-auto rounded-full","bg-gradient-to-r from-amber-50 to-orange-50 dark:from-amber-900/20 dark:to-orange-900/20","border-amber-200 dark:border-amber-700/50","hover:from-amber-100 hover:to-orange-100 dark:hover:from-amber-900/30 dark:hover:to-orange-900/30","transition-all duration-200",r),children:[(0,jn.jsxs)("div",{className:"relative",children:[(0,jn.jsx)(ne,{className:"w-4 h-4 text-amber-600 dark:text-amber-400"}),s&&(0,jn.jsx)("div",{className:"absolute inset-0 animate-ping",children:(0,jn.jsx)(ne,{className:"w-4 h-4 text-amber-600/50"})})]}),(0,jn.jsx)("span",{className:"font-semibold text-amber-700 dark:text-amber-300",children:s?"...":n?(0,jn.jsxs)("span",{className:"flex items-center gap-1 text-red-500",onClick:e=>{e.stopPropagation(),o()},title:"Failed to load credits. Click to retry.",children:[(0,jn.jsx)(A,{className:"w-3 h-3"}),(0,jn.jsx)(x,{className:"w-3 h-3"})]}):(l=a,l>=1e3?`${(l/1e3).toFixed(1)}k`:l.toString())}),!i?.is_personal&&i&&(0,jn.jsx)("span",{className:"text-xs text-amber-600/70 dark:text-amber-400/70 max-w-[60px] truncate",children:i.owner_name}),t&&(0,jn.jsx)(Fe,{className:"w-3 h-3 text-amber-600/50 dark:text-amber-400/50"})]});var l}var Vc=({open:e,onOpenChange:t,onSuccess:r})=>{const{t:a,tn:s}=at(),[n,i]=(0,fn.useState)(""),[o,l]=(0,fn.useState)(!1),c=async()=>{if(n.trim()){l(!0);try{const{data:e,error:o}=await Lt.functions.invoke("redeem-gift-code",{body:{code:n.trim()}});if(o)throw o;if(e.error)return void Ae.error(e.error);if("subscription"===e.reward_type){const t=e.subscription_tier.charAt(0).toUpperCase()+e.subscription_tier.slice(1);Ae.success(e.message||s("credits.gift_redeemed_months",e.subscription_months,{tier:t}),{icon:(0,jn.jsx)(ae,{className:"w-4 h-4 text-purple-500"}),duration:5e3})}else Ae.success(e.message||a("credits.gift_redeemed_credits",{count:e.credits_granted}),{icon:(0,jn.jsx)(ne,{className:"w-4 h-4 text-amber-500"})});i(""),t(!1),Fr(),r?.(e)}catch(e){Ge.error("Failed to redeem code:",e);let t=a("credits.gift_redeem_failed");if(e?.context?.body)try{const r=await e.context.body.json();r?.error&&(t=r.error)}catch{}else e?.message&&(t=e.message);Ae.error(t)}finally{l(!1)}}else Ae.error(a("credits.gift_code_required"))};return(0,jn.jsx)(xt,{open:e,onOpenChange:t,children:(0,jn.jsxs)(ht,{className:"sm:max-w-md",children:[(0,jn.jsxs)(mt,{children:[(0,jn.jsxs)(ft,{className:"flex items-center gap-2",children:[(0,jn.jsx)(Y,{className:"w-5 h-5 text-primary"}),"Redeem Gift Code"]}),(0,jn.jsx)(gt,{children:"Enter your gift code to receive credits or a subscription package"})]}),(0,jn.jsx)("div",{className:"py-4",children:(0,jn.jsx)(Et,{value:n,onChange:e=>
2i(e.target.value.toUpperCase()),placeholder:"Enter your code (e.g., WELCOME100)",className:"font-mono text-center text-lg tracking-wider",maxLength:20,onKeyDown:e=>"Enter"===e.key&&c()})}),(0,jn.jsxs)(pt,{children:[(0,jn.jsx)(Ye,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),(0,jn.jsx)(Ye,{onClick:c,disabled:o||!n.trim(),children:o?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)(ce,{className:"w-4 h-4 mr-2 animate-spin"}),"Redeeming..."]}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)(se,{className:"w-4 h-4 mr-2"}),"Redeem"]})})]})]})})};function Bc({children:e}){const[t,r]=(0,fn.useState)(!1),[a,s]=(0,fn.useState)(!1),[n,i]=(0,fn.useState)(!1),[o,l]=(0,fn.useState)([]),[d,m]=(0,fn.useState)(!1),{wallet:p,balance:h,getTransactionHistory:f,refreshWallet:g,loading:_,refreshing:b}=Wr();(0,fn.useEffect)(()=>{t&&p&&j()},[t,p]);const j=async()=>{m(!0);try{const e=await f(20,0);l(e)}finally{m(!1)}},v=e=>{const t={purchase:{label:"Purchase",variant:"default"},bonus:{label:"Bonus",variant:"secondary"},usage:{label:"Spent",variant:"destructive"},refund:{label:"Refund",variant:"outline"}}[e]||{label:e,variant:"outline"};return(0,jn.jsx)(Pr,{variant:t.variant,className:"text-xs",children:t.label})};return(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsxs)(lr,{open:t,onOpenChange:r,children:[(0,jn.jsx)(_r,{asChild:!0,children:e||(0,jn.jsx)(zc,{})}),(0,jn.jsxs)(rr,{className:"w-full sm:max-w-md overflow-y-auto",children:[(0,jn.jsx)(tr,{children:(0,jn.jsxs)(sr,{className:"flex items-center gap-2",children:[(0,jn.jsx)(ne,{className:"w-5 h-5 text-amber-500"}),"Credits Wallet"]})}),(0,jn.jsxs)("div",{className:"mt-6 space-y-6",children:[(0,jn.jsxs)("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-amber-500 to-orange-600 p-6 text-white",children:[(0,jn.jsx)("div",{className:"absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2"}),(0,jn.jsx)("div",{className:"absolute bottom-0 left-0 w-24 h-24 bg-white/10 rounded-full translate-y-1/2 -translate-x-1/2"}),(0,jn.jsxs)("div",{className:"relative",children:[(0,jn.jsx)("p",{className:"text-sm text-white/80 mb-1",children:"Current Balance"}),(0,jn.jsx)("p",{className:"text-4xl font-bold mb-4",children:_?"...":h.toLocaleString()}),(0,jn.jsxs)("p",{className:"text-sm text-white/70 flex items-center gap-1",children:[(0,jn.jsx)(Pe,{className:"w-3 h-3"})," Personal Wallet"]})]})]}),(0,jn.jsxs)("div",{className:"flex gap-2",children:[(0,jn.jsxs)(Ye,{onClick:()=>s(!0),className:"flex-1 gap-2 bg-amber-600 hover:bg-amber-700",children:[(0,jn.jsx)(Ee,{className:"w-4 h-4"}),"Top Up"]}),(0,jn.jsxs)(Ye,{variant:"outline",onClick:()=>i(!0),className:"flex-1 gap-2",children:[(0,jn.jsx)(Y,{className:"w-4 h-4"}),"Redeem Code"]}),(0,jn.jsx)(Ye,{variant:"outline",size:"icon","aria-label":"Refresh balance and history",title:"Refresh balance and history",onClick:()=>{g(),j()},children:(0,jn.jsx)(x,{className:He("w-4 h-4",(_||b)&&"animate-spin"),"aria-hidden":"true"})})]}),(0,jn.jsx)(ia,{compact:!0,onPurchaseStart:()=>{},onPurchaseComplete:()=>{g(),j()}}),(0,jn.jsxs)("div",{className:"rounded-lg border bg-muted/30 p-4",children:[(0,jn.jsxs)("h3",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[(0,jn.jsx)(se,{className:"w-4 h-4 text-amber-500"}),"How Credits Work"]}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mb-3",children:"Credits power every AI feature in 1tab. Use them for:"}),(0,jn.jsxs)("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,jn.jsx)(se,{className:"w-3 h-3"}),(0,jn.jsx)("span",{children:"AI generation (5-10)"})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,jn.jsx)(he,{className:"w-3 h-3"}),(0,jn.jsx)("span",{children:"Image gen (10)"})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,jn.jsx)(u,{className:"w-3 h-3"}),(0,jn.jsx)("span",{children:"Voice synthesis (8)"})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-2 text-muted-foreground",children:[(0,jn.jsx)(c,{className:"w-3 h-3"}),(0,jn.jsx)("span",{children:"Analysis (2-5)"})]})]})]}),(0,jn.jsxs)("div",{children:[(0,jn.jsx)("h3",{className:"text-sm font-medium mb-3",children:"Transaction History"}),(0,jn.jsx)(_t,{className:"h-[200px]",children:d?(0,jn.jsx)("div",{className:"flex items-center justify-center py-8",children:(0,jn.jsx)(x,{className:"w-5 h-5 animate-spin text-muted-foreground"})}):0===o.length?(0,jn.jsxs)("div",{className:"text-center py-8 text-muted-foreground",children:[(0,jn.jsx)(Ue,{className:"w-8 h-8 mx-auto mb-2 opacity-50"}),(0,jn.jsx)("p",{children:"No transactions yet"})]}):(0,jn.jsx)("div",{className:"space-y-3",children:o.map(e=>(0,jn.jsxs)("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[(0,jn.jsx)("div",{className:He("w-8 h-8 rounded-full flex items-center justify-center shrink-0 mt-0.5",e.amount>0?"bg-green-100 dark:bg-green-900/30":"bg-red-100 dark:bg-red-900/30"),children:e.amount>0?(0,jn.jsx)(We,{className:"w-4 h-4 text-green-600 dark:text-green-400"}):(0,jn.jsx)(E,{className:"w-4 h-4 text-red-600 dark:text-red-400"})}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"font-medium text-sm truncate",children:e.description||e.type}),(0,jn.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5 mt-1",children:[v(e.type),(e.platform_source,null)]}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:pe(ne
2w Date(e.created_at),{addSuffix:!0})})]}),(0,jn.jsxs)("div",{className:He("font-semibold text-sm shrink-0",e.amount>0?"text-green-600":"text-red-600"),children:[e.amount>0?"+":"",e.amount]})]},e.id))})})]})]})]})]}),(0,jn.jsx)($r,{open:a,onOpenChange:s}),(0,jn.jsx)(Vc,{open:n,onOpenChange:i,onSuccess:()=>{g(),j()}})]})}function Gc({className:e}){const t=Ve(),{currentTier:r,loading:a}=Lr();return a||"free"!==r?.id?null:(0,jn.jsxs)(Ye,{size:"sm",onClick:()=>t("/pricing"),title:"Upgrade your plan",className:He("gap-1.5 h-auto py-1.5 px-3 rounded-full border-0 text-white font-semibold","bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600",e),children:[(0,jn.jsx)(me,{className:"w-3.5 h-3.5"}),(0,jn.jsx)("span",{className:"hidden sm:inline",children:"Upgrade"})]})}var Yc="offline-status",Jc="offline-edits-queued";async function Qc(e,t){const r=Ka();r&&await Pa(r,e,{keepMine:t})&&await nn(e,r)}var Zc=e=>{const[t,r]=(0,fn.useState)(()=>an()),[a,s]=(0,fn.useState)("idle"),[n,i]=(0,fn.useState)(0),[o,l]=(0,fn.useState)(0),[c,d]=(0,fn.useState)(null);(0,fn.useEffect)(()=>{const e=()=>r(!0),t=()=>r(!1);window.addEventListener("online",e),window.addEventListener("offline",t);const a=pn((e,t,r)=>{s(e),i(t),l(r)});return()=>{window.removeEventListener("online",e),window.removeEventListener("offline",t),a()}},[]),(0,fn.useEffect)(()=>{La(e??null)},[e]);const u=(0,fn.useRef)(0);u.current=n,(0,fn.useEffect)(()=>{let t=!1;const r=()=>{mn(e).then(e=>{t||(i(e.pending),l(e.conflicts))})};r();const a=Aa(r);return()=>{t=!0,a()}},[e]);const m=(0,fn.useRef)(0);(0,fn.useEffect)(()=>{if(e)return Fa(t=>{t.userId===e&&function(e,t){if("queued"===e.kind){if("unreachable"!==e.cause)return;const r=Date.now();if(r-t.current<6e4)return;return t.current=r,void Ae.warning(dt("offline.queued_title"),{id:Jc,description:dt("offline.queued_desc")})}if("synced"===e.kind)return Ae.dismiss(Jc),void Ae.success(e.projectName?ct("offline.replayed_changes",e.changes,{name:e.projectName}):ct("offline.sync_synced_changes",e.changes),{id:`offline-edits-synced-${e.projectId}`});const r="conflict"===e.failure;var a,s,n;Ae.error(e.projectName?dt("offline.failed_title",{name:e.projectName}):dt("offline.failed_title_unnamed"),{id:`offline-edits-failed-${e.projectId}`,duration:1/0,description:`${a=e.failure,s=e.titles,n=e.message,"conflict"===a?s.length>0?dt("offline.failed_conflict_desc_items",{items:s.map(e=>dt("offline.quoted_item",{text:e})).join(", ")}):dt("offline.failed_conflict_desc"):"access"===a?dt("offline.failed_access_desc"):n?dt("offline.failed_rejected_desc",{message:n}):dt("offline.failed_rejected_desc_plain")} ${dt("offline.failed_kept")}`,action:{label:dt(r?"offline.keep_mine":"action.retry"),onClick:()=>{Qc(e.projectId,r).catch(t=>Ge.error("Retrying offline edits failed",t,{projectId:e.projectId}))}}})}(t,m)})},[e]),(0,fn.useEffect)(()=>{e&&t&&sn()},[e,t]);const p=(0,fn.useRef)(!1);return(0,fn.useEffect)(()=>{t?p.current&&(p.current=!1,Ae.success(dt("offline.back_online"),{id:Yc,duration:4e3,description:dt(u.current>0?"offline.back_online_syncing":"offline.back_online_desc")})):(p.current=!0,Ae.dismiss(Jc),Ae.warning(dt("offline.notice_title"),{id:Yc,duration:1/0,description:dt("offline.notice_desc")}))},[t]),(0,fn.useEffect)(()=>()=>{Ae.dismiss(Yc)},[]),(0,fn.useEffect)(()=>{let r,a=!1;return t&&e&&(r=(e=>{if("undefined"==typeof window)return()=>{};const t=window;if(t.requestIdleCallback&&t.cancelIdleCallback){const r=t.requestIdleCallback(e,{timeout:5e3});return()=>t.cancelIdleCallback?.(r)}const r=window.setTimeout(e,2500);return()=>window.clearTimeout(r)})(()=>{dn(e,{includeTemplates:!1,maxProjects:12}).then(e=>{e&&!a&&d(Date.now())})})),()=>{a=!0,r?.()}},[t,e]),{online:t,syncStatus:a,pendingCount:n,conflictCount:o,lastSyncTime:c,getProjectWithOffline:(0,fn.useCallback)(async e=>await Wa(e),[]),getAllProjectsWithOffline:(0,fn.useCallback)(async()=>$a(),[]),manualSync:(0,fn.useCallback)(async()=>{if(!an())return{success:!1,message:dt("offline.sync_while_offline")};en();const t=await un();if(ln())return{success:!0,message:dt("offline.sync_already_running")};const r=!!e&&await dn(e,{includeTemplates:!1,maxProjects:12}),a=await mn(e);return i(a.pending),l(a.conflicts),r&&d(Date.now()),t.failed>0||a.pending>0?{success:!1,message:ct("offline.sync_changes_failed",Math.max(t.failed,a.pending))}:r?{success:!0,message:t.synced>0?ct("offline.sync_synced_changes",t.synced):dt("offline.sync_up_to_date")}:{success:!1,message:dt("offline.sync_refresh_failed")}},[e]),addOfflineNote:(0,fn.useCallback)(async e=>{await Oa(e),t&&sn()},[t]),getOfflineNotes:(0,fn.useCallback)(async()=>Ra(),[]),removeOfflineNote:(0,fn.useCallback)(async e=>{await Ma(e)},[])}};function Xc(){const[e,t]=(0,fn.useState)([]);return(0,fn.useEffect)(()=>{let e=!1;const r=()=>{(async()=>{const r=Ka(),a=r?await Ea(r):[],s=await Promise.all(a.filter(e=>"failed"===e.status).map(async e=>({projectId:e.projectId,projectName:await Ta(e.projectId,e),failure:e.failure??"rejected",changes:Ha(e.patch),message:e.lastError})));e||t(s)})().catch(e=>Ge.warn("Could not list offline edits that were not applied",e))};r();const a=Aa(r);return()=>{e=!0,a()}},[]),e}var ed=({items:e,onDiscard:t})=>{const{t:r,tn:a}=at(),[s,n]=(0,fn.useState)(null);if(0===e.length)return null;const i=e=>"conflict"===e.failure?r("offline.failed_item_conflict"):"access"===e.failure?r("offline.failed_item_access"):r("offline.failed_item_rejected");return(0,jn.jsxs)("div",{className:"space-y-2",children:[(0,jn.jsx)("p",{className:"text-xs font-medium",children:r("offline.failed_list_title")}),(0,jn.jsx)("ul",{className:"space-y-2",children:e.map(e=>(0,jn.jsxs)("li",{className:"rounded-md border border-border p-2 space-y-1.5",children:[(0,jn.jsx)("p",{className:"text-sm font-medium break-words",children:e.projectName??r("offline.unknown_project")}),(0,jn.jsxs)("p",{className:"text-xs text-muted-foreground",children:[i(e)," · ",a("offline.failed_item_changes",e.changes)]}),(0,jn.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,jn.jsx)(Ye,{size:"sm",variant:"outline",className:"h-7",disabled:s===e.projectId,onClick:()=>{(async e=>{n(e.projectId);try{await Qc(e.projectId,"conflict"===e.failure)}catch(t){Ge.error("Retrying offline edits failed",t,{projectId:e.projectId}),Ae.error(r("offline.sync_failed_toast"))}finally{n(null)}})(e)},children:"conflict"===e.failure?r("offline.keep_mine"):r("action.retry")}),(0,jn.jsx)(Ye,{size:"sm",variant:"ghost",className:"h-7",onClick:()=>t(e),children:r("offline.discard")})]})]},e.projectId))})]})},td=({target:e,onClose:t})=>{const{t:r}=at(),a=async()=>
2{if(t(),e)try{await async function(e){const t=Ka();t&&await Ba(t,e)}(e.projectId),Ae.success(r("offline.discarded"))}catch(a){Ge.error("Discarding offline edits failed",a,{projectId:e.projectId}),Ae.error(r("offline.discard_failed"))}};return(0,jn.jsx)(Ct,{open:!!e,onOpenChange:e=>{e||t()},children:(0,jn.jsxs)(wt,{children:[(0,jn.jsxs)(It,{children:[(0,jn.jsx)(yt,{children:r("offline.discard_confirm_title")}),(0,jn.jsx)(vt,{children:r("offline.discard_confirm_desc")})]}),(0,jn.jsxs)(kt,{children:[(0,jn.jsx)(St,{children:r("action.cancel")}),(0,jn.jsx)(Nt,{onClick:()=>{a()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:r("offline.discard")})]})]})})},rd=({online:e,syncStatus:t,pendingCount:r,conflictCount:a=0,lastSyncTime:s,onSync:i,compact:o=!1})=>{const{t:l,tn:c}=at(),[d,u]=(0,fn.useState)(!1),m=d||"syncing"===t,p=l("offline.copy"),h=Xc(),[f,g]=(0,fn.useState)(null),_=e=>{if(!e)return l("offline.never");const t=Date.now()-e;return t<6e4?l("offline.just_now"):t<36e5?l("offline.minutes_ago",{count:Math.floor(t/6e4)}):t<864e5?l("offline.hours_ago",{count:Math.floor(t/36e5)}):new Date(e).toLocaleDateString()},b=()=>e?m?(0,jn.jsx)(x,{className:"w-4 h-4 animate-spin","aria-hidden":"true"}):a>0||"error"===t?(0,jn.jsx)(A,{className:"w-4 h-4","aria-hidden":"true"}):r>0?(0,jn.jsx)(B,{className:"w-4 h-4","aria-hidden":"true"}):(0,jn.jsx)(n,{className:"w-4 h-4","aria-hidden":"true"}):(0,jn.jsx)(Me,{className:"w-4 h-4","aria-hidden":"true"}),j=()=>e?a>0||"error"===t?"text-destructive-strong bg-destructive/10":m?"text-info-strong bg-info/10":r>0?"text-warning-strong bg-warning/10":"text-success-strong bg-success/10":"text-warning-strong bg-warning/10",v=()=>e?m?l("offline.status_syncing"):a>0?c("offline.status_conflicts",a):"error"===t?l("offline.status_sync_failed"):r>0?l("offline.status_pending",{count:r}):l("offline.status_synced"):l("offline.status_offline"),y=e&&i&&(0,jn.jsxs)(Ye,{size:"sm",variant:"outline",onClick:async()=>{if(i&&!m){u(!0);try{const e=await i();e&&(e.success?Ae.success(e.message):Ae.error(e.message))}catch(e){Ge.error("Manual sync failed",e),Ae.error(l("offline.sync_failed_toast"))}finally{u(!1)}}},disabled:m,className:"h-8 gap-1.5",children:[(0,jn.jsx)(x,{className:He("w-3.5 h-3.5",m&&"animate-spin"),"aria-hidden":"true"}),l(m?"offline.syncing":"offline.sync_now")]});return o?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsxs)(ca,{children:[(0,jn.jsx)(oa,{asChild:!0,children:(0,jn.jsxs)("button",{type:"button","aria-label":l("offline.status_aria",{status:v()}),className:He("flex items-center gap-1 px-2 py-1 rounded-full text-xs font-medium","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",j()),children:[b(),r>0&&(0,jn.jsx)("span",{children:r})]})}),(0,jn.jsxs)(la,{align:"end",className:"w-72 space-y-2 text-sm",children:[(0,jn.jsx)("p",{className:"font-medium",children:v()}),(0,jn.jsx)("p",{className:"text-muted-foreground",children:l("offline.last_sync",{time:_(s)})}),a>0&&(0,jn.jsx)("p",{className:"text-destructive-strong",children:l("offline.conflict_note")}),!e&&(0,jn.jsx)("p",{className:"text-warning-strong",children:p}),(0,jn.jsx)(ed,{items:h,onDiscard:g}),y]})]}),(0,jn.jsx)(td,{target:f,onClose:()=>g(null)})]}):(0,jn.jsxs)("div",{className:He("flex items-center gap-2 px-3 py-2 rounded-lg",j()),children:[b(),(0,jn.jsxs)("div",{className:"flex-1",children:[(0,jn.jsx)("p",{className:"text-sm font-medium",children:v()}),(0,jn.jsx)("p",{className:"text-xs",children:l("offline.last_sync",{time:_(s)})})]}),y,!e&&(0,jn.jsxs)("div",{className:"text-right",children:[(0,jn.jsx)(Pr,{variant:"outline",className:"text-xs bg-transparent border-current",children:l("offline.status_offline")}),(0,jn.jsx)("p",{className:"text-xs mt-0.5",children:p})]})]})},ad="module_last_seen_";function sd(e,t){try{return localStorage.getItem(`${ad}${e}_${t}`)}catch{return null}}function nd(e,t){try{localStorage.setItem(`${ad}${e}_${t}`,(new Date).toISOString())}catch{}}var id=({open:e,onOpenChange:t,onResend:r,resending:a,actionDescription:s})=>{const{t:n}=at(),i=s??n("emailverify.default_action");return(0,jn.jsx)(Ct,{open:e,onOpenChange:t,children:(0,jn.jsxs)(wt,{className:"max-w-md",children:[(0,jn.jsxs)(It,{className:"text-center sm:text-center",children:[(0,jn.jsx)("div",{className:"mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-primary/10",children:(0,jn.jsx)(V,{className:"h-7 w-7 text-primary"})}),(0,jn.jsx)(yt,{className:"text-xl",children:n("emailverify.title")}),(0,jn.jsx)(vt,{className:"text-center",children:n("emailverify.body",{action:i})})]}),(0,jn.jsxs)(kt,{className:"flex-col gap-2 sm:flex-col",children:[(0,jn.jsx)(Ye,{onClick:async()=>{await r()&&t(!1)},disabled:a,className:"w-full",children:a?(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)(ce,{className:"mr-2 h-4 w-4 animate-spin"}),n("emailverify.sending")]}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)(V,{className:"mr-2 h-4 w-4"}),n("emailverify.resend")]})}),(0,jn.jsx)(Ye,{variant:"ghost",onClick:()=>t(!1),className:"w-full",children:n("emailverify.later")})]})]})})},od=({onResend:e,resending:t})=>{const[r,a]=(0,fn.useState)(!1);return r?null:(0,jn.jsxs)("div",{className:"bg-amber-500/15 border-b border-amber-500/30 px-4 py-2.5 flex items-center justify-between gap-3",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 text-sm text-amber-700 dark:text-amber-300",children:[(0,jn.jsx)(V,{className:"w-4 h-4 shrink-0"}),(0,jn.jsx)("span",{children:"Please verify your email to unlock all features."}),(0,jn.jsx)(Ye,{variant:"ghost",size:"sm",onClick:e,disabled:t,className:"text-amber-700 dark:text-amber-300 hover:text-amber-900 dark:hover:text-amber-100 h-auto py-0.5 px-2 text-sm underline",children:t?(0,jn.jsx)(ce,{className:"w-3 h-3 animate-spin"}):"Resend email"})]}),(0,jn.jsx)("button",{type:"button",onClick:()=>a(!0),"aria-label":"Dismiss email verification reminder",className:"text-amber-600 dar
2k:text-amber-400 hover:text-amber-800 dark:hover:text-amber-200",children:(0,jn.jsx)(J,{className:"w-4 h-4","aria-hidden":"true"})})]})},ld={task_created:"created task",task_updated:"updated task",task_deleted:"deleted task",module_updated:"updated",version_created:"saved a version",member_invited:"invited a member",project_updated:"updated project",tasks_restored:"restored tasks"},cd={critical:3,warning:2,info:1};var dd=(e,t,r)=>(0,fn.useMemo)(()=>{if(!e)return null;const a=[];if(e.financials&&e.financials.length>0){const t=e.financials[0];t?.cac&&t?.ltv&&t.cac>t.ltv&&a.push({id:"cac-ltv",coachName:"Growth Advisor",coachEmoji:"ð",message:"Your CAC exceeds LTV â your unit economics may not be sustainable.",triggerModule:jt.FINANCIALS,severity:"critical",prefilledPrompt:"My customer acquisition cost exceeds lifetime value. What strategies can improve my unit economics?"})}e.refinedPitch&&!e.marketResearch&&a.push({id:"no-market-research",coachName:"Strategy Advisor",coachEmoji:"ð¯",message:"You have a pitch but no market research â validate your assumptions before building.",triggerModule:jt.IDEATION,severity:"warning",prefilledPrompt:"I have my startup pitch ready but haven't done market research yet. What should I validate first?"}),!e.strategy||e.financials&&0!==e.financials.length||a.push({id:"no-financials",coachName:"Finance Advisor",coachEmoji:"ð°",message:"Strategy is set but financials are missing â model your revenue before pitching.",triggerModule:jt.STRATEGY,severity:"warning",prefilledPrompt:"I have my business strategy defined. Help me think through my financial model â what projections should I create?"}),t!==jt.PITCH_DECK||e.strategy||e.marketResearch||a.push({id:"premature-pitch",coachName:"Pitch Coach",coachEmoji:"ð¤",message:"Building a pitch deck without strategy and market data will produce weak slides.",triggerModule:jt.PITCH_DECK,severity:"warning",prefilledPrompt:"I want to create a pitch deck but haven't completed my strategy or market research. What's the minimum I need?"});const s=(e.tasks||[]).filter(e=>!e.archivedAt),n=(e.okrs?.objectives||[]).filter(e=>!e.isArchived).length>0;s.length>10&&!n&&a.push({id:"tasks-no-okrs",coachName:"Execution Coach",coachEmoji:"ð",message:"You have many tasks but no OKRs â set goals to prioritize what matters.",triggerModule:jt.TASKS,severity:"info",prefilledPrompt:"I have many tasks but no clear OKRs. Help me define 2-3 key objectives to focus my effort."}),e.product&&!e.team&&a.push({id:"no-team",coachName:"HR Advisor",coachEmoji:"ð¥",message:"Product is defined but team isn't planned â identify key hires for execution.",triggerModule:jt.PRODUCT,severity:"info",prefilledPrompt:"My product vision is ready. What key roles should I hire first to start building?"});const i=(new Date).toISOString().split("T")[0],o=s.filter(e=>!(!e.dueDate||"DONE"===e.status)&&e.dueDate<i);if(o.length>=3&&a.push({id:"overdue-tasks",coachName:"Execution Coach",coachEmoji:"â°",message:`You have ${o.length} overdue tasks â want help reprioritizing?`,triggerModule:jt.TASKS,severity:"warning",prefilledPrompt:`I have ${o.length} overdue tasks. Help me reprioritize and decide what to defer, delegate, or drop.`}),n){const t=(e.okrs?.objectives||[]).filter(e=>{if(e.isArchived)return!1;const t=e.keyResults||[];return(t.length>0?t.reduce((e,t)=>e+(t.current||0)/(t.target||100)*100,0)/t.length:0)<20});t.length>0&&a.push({id:"stalled-okrs",coachName:"Strategy Advisor",coachEmoji:"ð",message:`${t.length} OKR(s) are under 20% progress â review your key results.`,triggerModule:jt.OKRS,severity:"info",prefilledPrompt:`I have ${t.length} OKRs with very low progress. Help me identify blockers and create action plans.`})}if(r?.meetingCount&&r.meetingCount>0&&r?.pendingActionItems&&r.pendingActionItems>3&&a.push({id:"unprocessed-meeting-items",coachName:"Meeting Coach",coachEmoji:"ðï¸",message:`${r.pendingActionItems} meeting action items haven't been turned into tasks yet.`,triggerModule:jt.MEETINGS,severity:"warning",prefilledPrompt:"Show me recent meeting action items that haven't been converted to tasks yet."}),0===r?.upcomingEventsCount&&s.length>5&&a.push({id:"empty-calendar",coachName:"Productivity Coach",coachEmoji:"ð
",message:"No meetings scheduled this week â consider a team sync to stay aligned.",triggerModule:jt.CALENDAR,severity:"info",prefilledPrompt:"I have no meetings this week. Should I schedule a team sync? Help me plan an effective standup."}),n&&s.length>5){const e=s.filter(e=>!e.linkedKeyResultId).length;e>8&&a.push({id:"unlinked-tasks",coachName:"Alignment Coach",coachEmoji:"ð",message:`${e} tasks aren't linked to OKRs â link them for better alignment.`,triggerModule:jt.TASKS,severity:"info",prefilledPrompt:`I have ${e} tasks not linked to any OKR. Help me identify which tasks align with my objectives.`})}const l=r?.crm?.staleDealCount??0,c=r?.crm?.closingThisWeekCount??0;return l>=3&&a.push({id:"crm-stale-deals",coachName:"Sales Coach",coachEmoji:"â³",message:`${l} open deals haven't moved in 14+ days â time to follow up.`,triggerModule:jt.CRM,severity:"warning",prefilledPrompt:"Call find_stale_deals with days=14 and tell me the top 3 I should act on today. For each, offer to log a follow-up activity and set a reminder."}),c>0&&a.push({id:"crm-closing-this-week",coachName:"Sales Coach",coachEmoji:"â°",message:`${c} deal(s) have expected close dates in the next 7 days.`,triggerModule:jt.CRM,severity:"info",prefilledPrompt:"Which deals are expected to close in the next 7 days, and what's blocking each one? Pull list_crm_deals filtered by stage and suggest a next action per deal."}),function(e,t){return 0===e.length?null:e.map((e,t)=>({s:e,i:t})).sort((e,r)=>{const a=cd[r.s.severity]-cd[e.s.severity];if(0!==a)return a;const s=e.s.triggerModule===t?1:0,n=r.s.triggerModule===t?1:0;return s!==n?n-s:e.i-r.i})[0].s}(a,t)},[e,t,r?.meetingCount,r?.pendingActionItems,r?.upcomingEventsCount,r?.crm?.staleDealCount,r?.crm?.closingThisWeekCount]);function ud(e,t){const{user:r}=$t(),a=(0,fn.useRef)(null);(0,fn.useEffect)(()=>
2{if(!e||!r||!t)return;if(a.current===t.id)return;const s=()=>{a.current=t.id,async function(e,t,r){const a=new Date(Date.now()-864e5).toISOString(),{data:s,error:n}=await Lt.from("personal_assistant_conversations").select("id, created_at, metadata").eq("project_id",e).eq("user_id",t).eq("role","assistant").gte("created_at",a).contains("metadata",{proactive:!0,suggestion_key:r.id}).limit(1);if(n)return Ge.error("Proactive cooldown check failed:",n),!1;if(s&&s.length>0)return!1;const i=new Date(Date.now()-12096e5).toISOString(),{data:o,error:l}=await Lt.from("personal_assistant_conversations").select("id").eq("project_id",e).eq("user_id",t).eq("role","assistant").gte("created_at",i).contains("metadata",{proactive:!0,suggestion_key:r.id}).order("created_at",{ascending:!1}).limit(5);if(l)Ge.error("Proactive dismissal lookup failed:",l);else if(o&&o.length>0){const e=o.map(e=>e.id),{data:r,error:a}=await Lt.from("pa_message_feedback").select("message_id").eq("user_id",t).eq("rating","down").in("message_id",e).limit(1);if(a)Ge.error("Proactive dismissal feedback check failed:",a);else if(r&&r.length>0)return!1}const c={proactive:!0,suggestion_key:r.id,coach_name:r.coachName,coach_emoji:r.coachEmoji,severity:r.severity,trigger_module:String(r.triggerModule),prefilled_prompt:r.prefilledPrompt},d=`${r.coachEmoji} **${r.coachName}**\n\n${r.message}`,{error:u}=await Lt.from("personal_assistant_conversations").insert({project_id:e,user_id:t,role:"assistant",content:d,metadata:c,read_at:null});return!u||(Ge.error("Failed to insert proactive message:",u),!1)}(e,r.id,t).catch(e=>{Ge.error("Proactive dispatch failed:",e)})},n=new Date,i=n.getHours();if(i<7||i>=22){const e=new Date(n);i>=22&&e.setDate(e.getDate()+1),e.setHours(7,0,0,0);const t=setTimeout(s,e.getTime()-n.getTime());return()=>clearTimeout(t)}s()},[e,r,t])}var md=t({default:()=>ku}),pd=it(()=>qe(()=>import("./TaskManager-BHlxdUWP.js").then(e=>({default:e.TaskManager})),__vite__mapDeps([62,1,2,3,4,5,6,7,8,9,10,11,12,63,64,65,13,14,66,27,50,23,54,67,15,16,17,18,19,20,21,68,26,22,24,25,28,29,30,31,32,33,51,37,35,36,38,39,40,41,42,69,70,71,72,45,73,74,55,75,76,57,77,78,79,80,81,43,44,46,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98]))),hd=it(()=>qe(()=>import("./Notes-D-q6uGpm.js").then(e=>({default:e.Notes})),__vite__mapDeps([99,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,57,54,17,15,16,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,36,37,45,74,55,75,78,100,43,44,46,101,102,82,103,104,105,106,107,88,108,109,110,111,112,113,51,85,86,94,114,115,91,93,95,116]))),fd=it(()=>qe(()=>import("./OKRs-DMr0qGGK.js").then(e=>({default:e.OKRs})),__vite__mapDeps([117,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,54,67,15,16,17,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,51,36,37,42,41,69,70,71,72,45,73,74,55,75,76,57,78,79,80,81,44,46,101,82,110,85,87,118,97,119,88,90,120,121,122,33,100,43,123,124,91,125,116,126,127,96,35,38,39,40,95,94,128]))),gd=it(()=>qe(()=>import("./Ideation-BUm_r9kq.js").then(e=>({default:e.Ideation})),__vite__mapDeps([129,1,2,3,4,5,6,7,8,9,10,11,12,14,66,27,50,23,54,15,26,16,17,18,19,20,21,22,24,25,28,29,30,31,32,51,36,37,42,41,69,73,79,68,78,80,100,13,45,43,44,46,101,130,131,132,90,133,122,33,72,75,77,123,134,135,136]))),xd=it(()=>qe(()=>import("./MarketResearch-guA8_3Vn.js").then(e=>({default:e.MarketResearch})),__vite__mapDeps([137,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,138,27,50,23,54,15,16,17,18,19,20,21,25,26,22,24,28,29,30,31,32,51,36,37,42,41,122,33,69,73,55,75,79,68,78,80,82,139,130,131,140,108,121,100,45,43,44,46,101,141,142,133,72,77,123,134,143,57,135,144,91,145,146]))),_d=it(()=>qe(()=>import("./BusinessStrategy-muSX_fjS.js").then(e=>({default:e.BusinessStrategy})),__vite__mapDeps([147,1,2,3,7,8,9,10,11,5,6,4,12,13,14,27,23,54,26,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,42,36,41,69,73,75,79,68,78,80,82,139,130,131,121,122,33,37,100,45,43,44,46,101,141,142,51,133,50,72,77,123,134,143,57,135,144]))),bd=it(()=>qe(()=>import("./ProductSpecs-Druyt6IX.js").then(e=>({default:e.ProductSpecs})),__vite__mapDeps([148,1,2,3,7,8,9,10,11,5,6,4,12,65,14,27,23,54,15,26,16,17,18,19,20,21,22,24,25,28,29,30,31,32,51,37,42,36,41,69,73,75,79,68,78,80,82,139,141,142,133,13,50,122,33,72,77,100,45,43,44,46,101,123,134,149,143,57,135,144,91,145,150]))),jd=it(()=>qe(()=>import("./MarketingHub-vFLFp5qB.js").then(e=>({default:e.MarketingHub})),__vite__mapDeps([151,1,2,3,7,8,9,10,11,5,6,4,12,14,66,23,26,27,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,42,36,41,79,68,73,78,80,133,13,50,51,37,122,33,69,72,75,77,100,45,43,44,46,101,123,134]))),vd=it(()=>qe(()=>import("./Financials-CZAjJWoh.js").then(e=>({default:e.Financials})),__vite__mapDeps([152,1,2,3,11,5,6,7,4,10,9,8,12,63,64,14,23,26,27,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,42,36,41,45,13,79,68,73,78,80,139,130,131,141,142,51,75,133,50,37,122,33,69,72,77,100,43,44,46,101,123,134,143,57,135,153,125]))),yd=it(()=>qe(()=>import("./FinanceDashboard-LZoEO94b.js").then(e=>({default:e.FinanceDashboard}
2)),__vite__mapDeps([154,1,2,3,7,11,5,6,4,10,9,8,12,63,64,13,14,66,23,54,26,27,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,37,69,73,55,76,57,78,79,68,80,81,139,83,140,118,92,155,156,42,36,41,77,153,125]))),wd=it(()=>qe(()=>import("./Investors-nzai0sul.js").then(e=>({default:e.Investors})),__vite__mapDeps([157,1,2,3,8,9,10,11,5,6,7,4,12,63,64,14,54,26,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,158,159,37,71,72,160,73,74,55,76,57,77,79,68,78,80,81,140,161,123,50,122,33,69]))),Nd=it(()=>qe(()=>import("./CustomerCRM-AbN04CGi.js").then(e=>({default:e.CustomerCRM})),__vite__mapDeps([162,1,2,3,4,5,6,7,8,9,10,11,12,63,64,14,27,50,54,15,16,17,18,19,20,21,68,29,25,26,23,22,24,28,30,31,32,51,37,69,72,160,73,74,55,75,76,57,77,78,79,80,81,100,13,45,43,44,46,101,83,140,84,114,124,163,110,103,104,164,91,92]))),kd=it(()=>qe(()=>import("./Mail-Cfml36Ms.js").then(e=>({default:e.Mail})),__vite__mapDeps([165,1,2,3,4,5,6,7,8,9,10,11,12,14,27,50,54,15,16,17,18,19,20,21,51,36,37,73,55,166,76,57,77,31,79,68,26,23,22,24,25,28,29,30,32,78,80,81,103,104,112]))),Sd=it(()=>qe(()=>import("./DemoMail-CiJtJrC8.js").then(e=>({default:e.DemoMail})),__vite__mapDeps([167,1,2,3,4,5,6,7,11,10,9,8,12,54,37,79,68,26,14,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,73,78,80]))),Id=it(()=>qe(()=>import("./Legal-NfJRDmud.js").then(e=>({default:e.Legal})),__vite__mapDeps([168,1,2,3,4,5,6,7,8,9,10,11,12,63,64,13,14,66,138,27,50,23,57,54,15,26,16,17,18,19,20,21,22,24,25,28,29,30,31,32,51,37,42,36,41,69,169,73,55,75,78,79,68,80,82,139,130,131,170,40,171,141,142,133,122,33,72,77,100,45,43,44,46,101,123,134,143,149,135,144]))),Cd=it(()=>qe(()=>import("./TeamStructure-B3U5RgK3.js").then(e=>({default:e.TeamStructure})),__vite__mapDeps([172,1,2,3,7,11,5,6,4,10,9,8,12,63,64,13,14,66,27,50,23,54,26,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,37,42,36,41,69,160,73,74,55,79,68,78,80,82,139,130,131,140,173,118,114,141,142,51,75,133,122,33,72,77,100,45,43,44,46,101,123,134,149,143,57,135,144,136]))),Ed=it(()=>qe(()=>import("./Fundraising-DRtg2UOs.js").then(e=>({default:e.Fundraising})),__vite__mapDeps([174,1,2,3,8,9,10,11,5,6,7,4,12,63,64,14,23,54,26,27,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,42,36,41,69,55,78,79,68,73,80,139,103,104,118,141,142,51,75,133,13,50,37,122,33,72,77,100,45,43,44,46,101,123,134,149,143,57,135,155,125]))),Td=it(()=>qe(()=>import("./PitchDeck-ZRDlSb5c.js").then(e=>({default:e.PitchDeck})),__vite__mapDeps([175,1,2,3,4,5,6,7,8,9,10,11,12,63,64,13,14,27,50,23,54,15,16,17,18,19,20,21,26,22,24,25,28,29,30,31,32,42,36,41,69,73,55,78,79,68,80,82,139,130,131,115,105,106,141,142,51,75,133,37,122,33,72,77,100,45,43,44,46,101,123,134,135,91,176,150]))),Ad=it(()=>qe(()=>import("./AICoach-DuU_tzGo.js").then(e=>({default:e.AICoach})),__vite__mapDeps([177,1,2,3,4,5,6,7,8,9,10,11,12,13,14,27,50,23,54,15,68,26,16,17,18,19,20,21,22,24,25,28,29,30,31,32,37,42,36,41,69,169,178,45,55,75,77,80,100,43,44,46,101]))),Dd=it(()=>qe(()=>import("./HR-DWbViZx9.js").then(e=>({default:e.HR})),__vite__mapDeps([179,1,2,3,4,5,6,7,8,9,10,11,12,63,64,13,14,27,54,67,15,16,17,18,19,20,21,26,23,22,24,25,28,29,30,31,32,51,159,158,37,42,36,41,69,160,70,71,72,73,74,55,75,76,57,78,79,68,80,100,45,43,44,46,101,83,140,180,181,182]))),Od=it(()=>qe(()=>import("./RiskAnalysis-WOucsEBe.js").then(e=>({default:e.RiskAnalysis})),__vite__mapDeps([183,1,2,3,4,5,6,7,8,9,10,11,12,13,14,27,57,54,26,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,42,36,41,69,45,73,78,79,68,80,132,135,123,50,122,33,37]))),Rd=it(()=>qe(()=>import("./Pricing-RubEeSeK.js").then(e=>({default:e.Pricing})),__vite__mapDeps([156,1,2,3,11,5,6,7,4,10,9,8,12,13,14,54,26,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,42,36,41,69,73,55,77,79,68,78,80,81]))),Md=it(()=>qe(()=>import("./CustomerDiscovery-svFccKCE.js").then(e=>({default:e.CustomerDiscovery})),__vite__mapDeps([184,1,2,3,7,8,9,10,11,5,6,4,12,13,14,27,50,23,54,15,16,17,18,19,20,21,68,29,25,26,22,24,28,30,31,32,37,42,36,41,69,160,73,55,75,79,78,80,82,139,110,141,142,51,133,122,33,72,77,100,45,43,44,46,101,123,134,143,57,149,135,144,163,103,104,124,164]))),Pd=it(()=>qe(()=>import("./WhiteboardResponsive-BAAwuR-U.js").then(e=>({default:e.WhiteboardResponsive}
2)),__vite__mapDeps([185,1,2,7,11,5,6,3,4,10,9,8,12,26,14,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32]))),Ld=it(()=>qe(()=>import("./MeetingNotes-C14y3WaX.js").then(e=>e.n).then(e=>({default:e.MeetingNotes})),__vite__mapDeps([186,1,2,3,4,5,6,7,8,9,10,11,12,63,64,14,27,57,54,15,16,17,18,19,20,21,25,26,23,22,24,28,29,30,31,32,33,40,13,41,70,71,72,45,73,74,55,77,78,79,68,80,81,100,43,44,46,101,102,82]))),Ud=it(()=>qe(()=>import("./CalendarModule-Bwfq9Fc_.js"),__vite__mapDeps([187,1,2,5,6,7,3,4,8,9,10,11,12,13,14,27,50,54,15,16,17,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,51,37,70,71,72,73,74,55,76,57,188,189,77,78,79,80,81,43,44,45,46,82,61,85]))),$d=it(()=>qe(()=>import("./GitHubModule-eaY9fN8e.js").then(e=>({default:e.GitHubModule})),__vite__mapDeps([190,1,2,3,4,5,6,7,8,9,10,11,12,14,54,26,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,37,45,13,73,191,189,192,79,68,78,80]))),Fd=it(()=>qe(()=>import("./Drive--pP69fp1.js").then(e=>({default:e.Drive})),__vite__mapDeps([193,1,2,3,4,5,6,7,11,10,9,8,12,14,66,27,57,54,26,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,158,159,37,45,13,78,79,68,73,80,88,182,36]))),Wd=it(()=>qe(()=>import("./PixelOffice-BJtj-uXS.js").then(e=>({default:e.PixelOffice})),__vite__mapDeps([194,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,23,54,15,16,17,18,19,20,21,25,26,22,24,28,29,30,31,32,36,40,41,42,69,45,74,75,76,57,80,110,112,127]))),Kd=it(()=>qe(()=>import("./TeamManagement-uXTLQuGA.js").then(e=>({default:e.TeamManagement})),__vite__mapDeps([195,1,2,3,8,9,10,11,5,6,7,4,12,14,27,54,15,16,17,18,19,20,21,35,36,37,38,39,40,13,25,41,42,70,28,23,71,72,73,76,57,196,50,22,24,130,131]))),Hd=it(()=>qe(()=>import("./PendingInvites-C-S_PEXV.js").then(e=>({default:e.PendingInvites})),__vite__mapDeps([197,1,2,3,8,9,10,11,5,6,7,4,12,13,14,66,27,50,54,15,16,17,18,19,20,21,33,37,35,36,38,39,40,25,41,42,71,72,169,178]))),qd=it(()=>qe(()=>import("./DeleteProjectDialog-DibEP9QF.js").then(e=>({default:e.DeleteProjectDialog})),__vite__mapDeps([198,1,2,57,5,6,7,4,11,3,10,9,8,12,54]))),zd=it(()=>qe(()=>import("./UsageLimitAlert-CnTfO0B8.js").then(e=>({default:e.UsageLimitAlert})),[])),Vd=it(()=>qe(()=>import("./NewsCenter-DUHrXx-p.js").then(e=>({default:e.NewsCenter})),__vite__mapDeps([199,1,2,3,11,5,6,7,4,10,9,8,12,50,26,14,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32,37]))),Bd=it(()=>qe(()=>import("./MobileBottomNav-SSFLkrx_.js").then(e=>e.n).then(e=>({default:e.MobileBottomNav})),__vite__mapDeps([200,1,2,3,4,5,6,7]))),Gd=it(()=>qe(()=>import("./MobileModuleDrawer-BCb4SXWZ.js").then(e=>e.n).then(e=>({default:e.MobileModuleDrawer})),__vite__mapDeps([201,1,2,3,4,5,6,7,11,10,9,8,12,14,50,23,22,15,19,24,16,17,18,20,21,25,26,27,28,29,30,31,32]))),Yd=it(()=>qe(()=>import("./Advertising-BeBB6RXk.js").then(e=>({default:e.Advertising})),__vite__mapDeps([202,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,57,54,15,16,17,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,51,36,37,42,41,69,73,55,75,78,79,80,85,120,114,115,105,106,121,122,33,100,45,43,44,46,101]))),Jd=it(()=>qe(()=>import("./WebsiteBuilder-C1kDgrar.js").then(e=>({default:e.WebsiteBuilder})),__vite__mapDeps([203,1,2,3,4,5,6,7,8,9,10,11,12,14,27,23,57,54,15,68,26,16,17,18,19,20,21,22,24,25,28,29,30,31,32,158,159,35,36,37,38,39,40,13,41,42,69,73,55,79,78,80,139,130,131,103,104,141,133,50,51,122,33,72,75,77,100,45,43,44,46,101,123,134,143,135]))),Qd=it(()=>qe(()=>import("./CompetitorWarRoom-BlaUHkUu.js").then(e=>({default:e.CompetitorWarRoom})),__vite__mapDeps([204,1,2,3,7,8,9,10,11,5,6,4,12,63,64,14,27,54,15,16,17,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,51,36,37,42,41,69,70,71,72,45,13,73,55,75,77,78,79,80,43,82]))),Zd=it(()=>qe(()=>import("./MobileMenu-DmwKIZZa.js").then(e=>({default:e.MobileMenu})),__vite__mapDeps([205,1,2,3,11,5,6,7,4,10,9,8,12,26,14,27,23,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32]))),Xd=it(()=>qe(()=>import("./BusinessPlanDialog-BpCbw_eJ.js").then(e=>({default:e.BusinessPlanDialog})),__vite__mapDeps([206,1,2,3,7,8,9,10,11,5,6,4,12,65,14,207,13,66,138,27]))),eu=it(()=>qe(()=>import("./onboarding-Byk_kXSF.js").then(e=>({default:e.OnboardingWizard})),__vite__mapDeps([53,1,2,3,4,5,6,7,11,10,9,8,12,27,54,51,55]))),tu=it(()=>qe(()=>import("./migration-C4BSyUBu.js").then(e=>e.t).then(e=>({default:e.MigrationHub})),__vite__mapDeps([208,1,2,3,8,9,10,11,5,6,7,4,12,209,14,66,27,15,16,17,18,19,20,21,73,55,43,101,45,
213,44,46,210]))),ru=it(()=>qe(()=>import("./CommunicationBoard-D2hN2uJF.js").then(e=>({default:e.CommunicationBoard})),__vite__mapDeps([211,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,57,54,17,67,15,16,18,19,20,21,68,25,29,26,23,22,24,28,30,31,32,51,34,36,37,42,41,69,72,160,45,73,74,55,75,77,78,100,43,44,46,101,82,131,212,85,86,213,87,214,105,106,107,112,97,119,88,94,108,89]))),au=it(()=>qe(()=>import("./ProjectSettingsDialog-BsenHkLa.js"),__vite__mapDeps([215,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,23,54,15,16,17,18,19,20,21,22,24,25,26,28,29,30,31,32,51,36,37,38,35,39,40,41,42,69,160,70,71,72,73,74,55,216,217,166,75,76,57,191,189,192,188,186,63,64,33,45,77,78,79,68,80,81,100,43,44,46,101,102,82,208,209,210,139,83,196]))),su=it(()=>qe(()=>import("./dashboard-CNA0CMUw.js").then(e=>({default:e.TodayView})),__vite__mapDeps([218,1,2,11,5,6,7,3,4,10,9,8,12,14,50,37,31,219,13,66,23,15,16,17,18,19,20,21,26,27,22,24,25,28,29,30,32,51,122,33,69,169,178,80,46,82,87,220,170,36,41,40,42,171,118]))),nu=it(()=>qe(()=>import("./GlobalCommandPalette-DV-PAbM0.js").then(e=>({default:e.GlobalCommandPalette})),__vite__mapDeps([221,1,2,3,8,9,10,11,5,6,7,4,12,14,23,17,67,27,15,16,18,19,20,21,68,22,24,25,26,28,29,30,31,32]))),iu=it(()=>qe(()=>import("./TeamPulse-C2KV1cGn.js").then(e=>({default:e.TeamPulse})),__vite__mapDeps([222,1,2,3,11,5,6,7,4,10,9,8,12,37,75,80,85,86]))),ou=it(()=>qe(()=>import("./FloatingQuickActions-BkTGoXCf.js").then(e=>({default:e.FloatingQuickActions})),__vite__mapDeps([223,1,2,3,4,5,6,7,33]))),lu=it(()=>qe(()=>import("./QuickTaskCapture-DEuirbvp.js").then(e=>({default:e.QuickTaskCapture})),[])),cu=it(()=>qe(()=>import("./PhaseContextBanner-BQt1gMpW.js").then(e=>({default:e.PhaseContextBanner})),__vite__mapDeps([224,1,2,3,11,5,6,7,4,10,9,8,12,14,23,26,27,15,16,17,18,19,20,21,22,24,25,28,29,30,31,32]))),du=it(()=>qe(()=>import("./ModuleBreadcrumb-BjAFlFxH.js").then(e=>({default:e.ModuleBreadcrumb})),__vite__mapDeps([225,1,2,3,11,5,6,7,4,10,9,8,12,14,22,23,15,19,24,16,17,18,20,21,25,78]))),uu=it(()=>qe(()=>import("./AssistantTopBarButton-xlywZ6Gs.js").then(e=>({default:e.AssistantTopBarButton})),__vite__mapDeps([226,1,2,4,5,6,7,8,9,10,11,3,12,14,15,16,17,18,19,20,21,34]))),mu=it(()=>qe(()=>import("./PeekPanel-CqJY5wxB.js").then(e=>({default:e.PeekPanel})),__vite__mapDeps([227,1,2,3,4,5,6,7,11,10,9,8,12,66,15,26,14,27,23,16,17,18,19,20,21,22,24,25,28,29,30,31,32,37]))),pu=it(()=>qe(()=>import("./PinStrip-mBiEJkEn.js").then(e=>({default:e.PinStrip})),__vite__mapDeps([228,1,2,3,4,5,6,7,11,10,9,8,12]))),hu=it(()=>qe(()=>import("./NextActionBanner-Dqbwy5oF.js").then(e=>({default:e.NextActionBanner})),__vite__mapDeps([229,1,2,3,4,5,6,7,11,10,9,8,12,14,16,17,15,18,19,20,21,33,122,37,69,30]))),fu=it(()=>qe(()=>import("./TeamCallsHost-CN9V1qle.js").then(e=>e.n).then(e=>({default:e.TeamCallsHost})),__vite__mapDeps([213,1,2,3,4,5,6,7,11,10,9,8,12,14,57,212,15,16,17,18,19,20,21,25,85,86]))),gu=new Set(["strategy","marketResearch","product","branding","growth","fundraising","legal","team","pitchDeck","financials","risks","okrs"]),xu=new Set([jt.MARKET_RESEARCH,jt.CUSTOMER_DISCOVERY,jt.STRATEGY,jt.PRODUCT,jt.TEAM,jt.MARKETING,jt.FINANCIALS,jt.LEGAL,jt.PITCH_DECK,jt.FUNDRAISING,jt.WEBSITE,jt.GROWTH,jt.FINANCE_DASHBOARD,jt.INVESTOR_PIPELINE,jt.RISK,jt.PRICING,jt.COMPETITOR_WAR_ROOM,jt.MENTOR,jt.GAME]),_u=(e,t,r,a)=>{const s={...e};for(const n of r)n in t&&!a(n)&&(s[n]=t[n]);return s},bu=({failed:e,onRetry:t})=>e?(0,jn.jsxs)("div",{className:"flex flex-col items-center justify-center gap-3 px-4 py-24 text-center",children:[(0,jn.jsx)("p",{className:"text-sm text-muted-foreground",children:"This module's saved data couldn't be loaded."}),(0,jn.jsx)(Ye,{variant:"outline",size:"sm",onClick:t,children:"Try again"})]}):(0,jn.jsx)(Nr,{}),ju=()=>{const e=D();return{id:D(),name:"New Startup",lastUpdated:Date.now(),ideaRaw:"",refinedPitch:"",targetAudience:"",problemStatement:"",proposedSolution:"",marketResearch:null,marketingStrategy:null,growth:null,strategy:null,branding:null,product:null,team:null,legal:null,fundraising:null,financials:[],pitchDeck:[],mentorChat:[],risks:[],milestones:[],boards:[{id:e,name:"Main Board",description:"General project tasks",createdAt:Date.now()}],tasks:[],customerDiscovery:null,okrs:{objectives:[]},language:st()}},vu=e=>{const t={...e};if(t.boards||(t.boards=[]),t.tasks||(t.tasks=[]),t.financials||(t.financials=[]),t.pitchDeck||(t.pitchDeck=[]),t.mentorChat||(t.mentorChat=[]),t.risks||(t.risks=[]),t.milestones||(t.milestones=[]),0===t.boards.length&&(t.boards=[{id:D(),name:"Main Board",description:"General project tasks",createdAt:Date.now()}]),t.marketingStrategy||(t.marketingStrategy=null),t.growth||(t.growth=null),t.fundraising||(t.fundraising=null),t.customerDiscovery||(t.customerDiscovery=null),t.marketResearch&&"object"==typeof t.marketResearch){const e=t.marketResearch;
2Array.isArray(e.competitors)||(e.competitors=[]),Array.isArray(e.personas)||(e.personas=[]),Array.isArray(e.trends)||(e.trends=[]),Array.isArray(e.comparisonDimensions)||(e.comparisonDimensions=[]),Array.isArray(e.validationMethods)||(e.validationMethods=[]),Array.isArray(e.sources)||(e.sources=[]),"string"!=typeof e.marketOverview&&(e.marketOverview=e.marketOverview?String(e.marketOverview):""),"string"!=typeof e.marketSize&&(e.marketSize=e.marketSize?String(e.marketSize):"")}if(t.strategy&&"object"==typeof t.strategy){const e=t.strategy;Array.isArray(e.revenueStreams)||(e.revenueStreams=[]),Array.isArray(e.costStructure)||(e.costStructure=[]),Array.isArray(e.keyPartners)||(e.keyPartners=[]),"string"!=typeof e.valueProposition&&(e.valueProposition=e.valueProposition?String(e.valueProposition):""),"string"!=typeof e.competitiveAdvantage&&(e.competitiveAdvantage=e.competitiveAdvantage?String(e.competitiveAdvantage):""),"string"!=typeof e.modelType&&(e.modelType=e.modelType?String(e.modelType):""),e.swot&&"object"==typeof e.swot&&(Array.isArray(e.swot.strengths)||(e.swot.strengths=[]),Array.isArray(e.swot.weaknesses)||(e.swot.weaknesses=[]),Array.isArray(e.swot.opportunities)||(e.swot.opportunities=[]),Array.isArray(e.swot.threats)||(e.swot.threats=[]))}return t},yu={display_name:"Player",avatar_emoji:"ð"},wu=[],Nu=()=>{const{user:e,loading:t,signOut:r}=$t(),{trackProject:a,trackFeature:n,trackLogout:i}=gs(),o=Ve(),l=Kt(),[c]=Be(),u=ze(),{isCollapsed:m}=hr(),[h,f]=(0,fn.useState)([]),g=(0,fn.useMemo)(()=>h.map(e=>e.id),[h]),[x,_]=(0,fn.useState)(null),[j,v]=(0,fn.useState)(!0),[y,w]=(0,fn.useState)(!1),[N,S]=(0,fn.useState)(null),[C,E]=(0,fn.useState)({projectId:null,status:"loading"}),T=!!x&&C.projectId===x.id&&"loaded"===C.status,A=!!x&&C.projectId===x.id&&"error"===C.status,[O,R]=(0,fn.useState)(null),[M,P]=(0,fn.useState)(null),[L,U]=(0,fn.useState)(null),[$,F]=(0,fn.useState)(null),[W,K]=(0,fn.useState)(null),H=(0,fn.useCallback)(()=>K(null),[]),[q,z]=(0,fn.useState)(null),V=(0,fn.useCallback)(()=>z(null),[]),[B,Y]=(0,fn.useState)(jt.IDEATION),Q=(0,fn.useRef)(B);Q.current=B;const Z=(0,fn.useRef)(null),ee=(0,fn.useRef)(!1),{navigateToModule:te,persistLastVisit:re,readLastVisit:ne}=oc(Y),{favorites:ie,recent:oe,recordVisit:le,toggleFavorite:de}=(e=>{const[t,r]=(0,fn.useState)(()=>Nc(e)),a=(0,fn.useRef)(!1);(0,fn.useEffect)(()=>{a.current=!1,r(Nc(e))},[e]),(0,fn.useEffect)(()=>{e&&a.current&&(a.current=!1,qr(wc(e),JSON.stringify(t)))},[e,t]);const s=(0,fn.useCallback)(e=>{r(t=>{const r=e(t);
2return r!==t&&(a.current=!0),r})},[]),n=(0,fn.useCallback)(e=>{s(t=>({...t,recent:vc(t.recent,e)}))},[s]),i=(0,fn.useCallback)(e=>{s(t=>({...t,favorites:yc(t.favorites,e)}))},[s]);return{favorites:t.favorites,recent:t.recent,recordVisit:n,toggleFavorite:i}})(x?.id??null),[ue,me]=(0,fn.useState)(jt.IDEATION),[he,fe]=(0,fn.useState)(jt.DASHBOARD),[ge,_e]=(0,fn.useState)({}),[ve,we]=(0,fn.useState)(()=>zr("1tab_theme")||"light"),[Ne,ke]=(0,fn.useState)(!1),[Se,Ce]=(0,fn.useState)(""),[Te,De]=(0,fn.useState)("all"),[Re,Me]=(0,fn.useState)(""),[Pe,Le]=(0,fn.useState)("lastEdited"),[Ue,$e]=(0,fn.useState)(null),[Fe,We]=(0,fn.useState)(!1),[Ke,Qe]=(0,fn.useState)(!1),[Ze,Xe]=(0,fn.useState)(!1),[tt,rt]=(0,fn.useState)(!1),[at,nt]=(0,fn.useState)(null),[it,lt]=(0,fn.useState)(!1),[ct,ut]=(0,fn.useState)(!1),[mt,pt]=(0,fn.useState)(!1),[ht,ft]=(0,fn.useState)(!1),[gt,xt]=(0,fn.useState)(""),_t=(0,fn.useRef)([]),[vt,yt]=(0,fn.useState)({open:!1,type:"task",id:""}),[wt,Nt]=(0,fn.useState)(null),[kt,St]=(0,fn.useState)(""),[It,Ct]=(0,fn.useState)(null),[Et,Tt]=(0,fn.useState)(!1),[At,Dt]=(0,fn.useState)(null),[Ot,Rt]=(0,fn.useState)({display_name:"Assad",avatar_emoji:"ð¤"}),[Mt,Pt]=(0,fn.useState)(null),Wt=(0,fn.useCallback)((e,t,r=null)=>{Dt(e),Rt(t),Pt(r),Tt(!0)},[]),Ht=(0,fn.useCallback)(()=>{Tt(!1),Dt(null),Pt(null)},[]),[Vt,Gt]=(0,fn.useState)("dashboard"),[Yt,Qt]=(0,fn.useState)(!1);(0,fn.useEffect)(()=>{x?.id&&le(B)},[B,x?.id,le]);const[Zt,ir]=(0,fn.useState)(null),[cr,yr]=(0,fn.useState)(!1),Or=(0,fn.useRef)(null),Mr=(0,fn.useRef)(!1),{totalUnreadCount:Pr,resetUnreadCount:$r}=function(e,t){const[r,a]=(0,fn.useState)(0);return(0,fn.useEffect)(()=>{if(!e||!t)return;let r=!1,s=null;const n=async()=>{try{const{data:s,error:n}=await Lt.rpc("get_unread_channel_counts",{p_user_id:t,p_project_id:e});if(n)return void Ge.error("Error fetching unread count",n,{projectId:e});if(!r&&s){const e=s.reduce((e,t)=>e+(Number(t.unread_count)||0),0);a(e)}}catch(s){Ge.error("Error fetching unread count:",s)}},i=()=>{s&&clearTimeout(s),s=setTimeout(()=>{s=null,n()},1500)};n();const o=Lt.channel(Jt(`sidebar-unread-${e}-${t}`)).on("postgres_changes",{event:"INSERT",schema:"public",table:"team_chat_messages",filter:`project_id=eq.${e}`},e=>{const r=e.new;r.user_id!==t&&mo(r.channel,t,r.user_id)&&i()}).on("postgres_changes",{event:"*",schema:"public",table:"channel_read_status",filter:`user_id=eq.${t}`},i).subscribe();return()=>{r=!0,s&&clearTimeout(s),Lt.removeChannel(o)}},[e,t]),{totalUnreadCount:r,resetUnreadCount:(0,fn.useCallback)(()=>{a(0)},[])}}(x?.id??null,e?.id??null),[Fr,Wr]=(0,fn.useState)([]),{mailVisible:Kr}=jr(),Hr=(0,fn.useMemo)(()=>!0===h.find(e=>e.id===x?.id)?.isTemplate,[h,x?.id]),{activations:Vr,loading:Br}=zt(),{isModuleAllowed:Zr,loading:Xr}=fr(x?.id??null),ea=bn(x?.id??null),ta=ea.isViewer,ra=ea.loading,aa=(0,fn.useRef)(!0);aa.current=null===ea.role||ea.canManageProject;const sa=!1===Vr[B]?.active,na=!Xr&&!Zr(B),ia=sa||na;(0,fn.useEffect)(()=>{if(!x||Br||Xr||!ia)return;const e=Bt(Vr,Zr);e&&e!==B&&(ee.current=!0,Y(e))},[B,ia,x,Xr,Zr,Vr,Br]);const[oa,la]=(0,fn.useState)(!1),[ca,da]=(0,fn.useState)(null),[ua,pa]=(0,fn.useState)(null),[ha,ba]=(0,fn.useState)(null),[ja,va]=(0,fn.useState)(()=>{try{return"true"===localStorage.getItem("transitionCoachDisabled")}catch{return!1}}),ya=h.find(e=>e.id===Ue),{canCreateProject:ka,loading:Ea}=Lr(),{showProjectLimitPaywall:Ta}=Ur(),{requireVerification:Aa,isVerified:Oa,showVerificationDialog:Ra,setShowVerificationDialog:Ma,pendingAction:Pa,resendVerificationEmail:La,resending:$a}=Ss();fs(x?B:"dashboard",x?.id);const{tasksHasNew:Fa,notesHasNew:Wa,whiteboardHasNew:Ka,markModuleSeen:Ha}=function(e){const[t,r]=(0,fn.useState)(!1),[a,s]=(0,fn.useState)(!1),[n,i]=(0,fn.useState)(!1),o=(0,fn.useRef)(null),l=(0,fn.useCallback)(async()=>{if(!e)return;const t=sd(e,"tasks"),a=sd(e,"notes"),n=sd(e,"whiteboard"),[o,l,c]=await Promise.all([t?Lt.from("project_activity_log").select("id",{count:"exact",head:!0}).eq("project_id",e).in("action",["task_created","task_updated","task_deleted","tasks_restored"]).gt("created_at",t):Promise.resolve({count:null}),a?Lt.from("project_documents").select("id",{count:"exact",head:!0}).eq("project_id",e).eq("is_archived",!1).gt("updated_at",a):Promise.resolve({count:null}),n?Lt.from("whiteboards").select("id",{count:"exact",head:!0}).eq("project_id",e).eq("is_archived",!1).gt("updated_at",n):Promise.resolve({count:null})]);"error"in o&&o.error&&Ge.error("useModuleActivity tasks count failed:",o.error),"error"in l&&l.error&&Ge.error("useModuleActivity notes count failed:",l.error),"error"in c&&c.error&&Ge.error("useModuleActivity whiteboards count failed:",c.error),t&&r((o.count??0)>0),a&&s((l.count??0)>0),n&&i((c.count??0)>0)},[e]);return(0,fn.useEffect)(()=>(l(),o.current=setInterval(l,3e4),()=>{o.current&&clearInterval(o.current)}),[l]),{tasksHasNew:t,notesHasNew:a,whiteboardHasNew:n,markModuleSeen:(0,fn.useCallback)(t=>{e&&(t===jt.TASKS?(nd(e,"tasks"),r(!1)):t===jt.NOTES?(nd(e,"notes"),s(!1)):t===jt.WHITEBOARD&&(nd(e,"whiteboard"),i(!1)))},[e])}}(x?.id??null);(0,fn.useEffect)(()=>{x&&Ha(B)},[B,x?.id,Ha]);const[Ba,xs]=(0,fn.useState)(()=>({current:B,previous:null}));Ba.current!==B&&xs({current:B,previous:Ba.current});const _s=Ba.previous;(0,fn.useEffect)(()=>{window.scrollTo({top:0,behavior:"instant"}),B===jt.COMMUNICATION?$r():F(null)},[B]);const js=(0,fn.useRef)(x);js.current=x;const vs=(0,fn.useRef)(new Map);if(x&&vs.current.get(x.id)!==x){const e=vs.current;for(e.delete(x.id),e.set(x.id,x);e.size>3;){const t=e.keys().next().value;if(void 0===t)break;e.delete(t)}}const ys=(0,fn.useRef)(0),ws=(0,fn.useRef)(new Map),ks=(0,fn.useCallback)((e,t,r)=>(ws.current.get(`${e}:${String(t)}`)??0)>r,[]),Is=(0,fn.useRef)(null),Cs=(0,fn.useCallback)(e=>{Is.current={projectId:e.id,okrs:e.okrs??{objectives:[]},version:null}},[]),Es=(0,fn.useRef)(0),Ts=(0,fn.useRef)(0),As=(0,fn.useRef)(null),Rs=(0,fn.useRef)(new Map),Ms=(0,fn.useRef)(!1),Ps=(0,fn.useRef)(h);Ps.current=h;const Ls=(0,fn.useRef)(()=>{});(0,fn.useEffect)(()=>{const e=(e,t)=>
2wr(e,t)&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!e.repeat&&!xr(e.target)&&!pr(e.target),t=nr(t=>e(t,"q"),e=>{js.current&&(Qr(js.current.id)||(e.preventDefault(),pt(!0)))}),r=nr(t=>e(t,"n"),e=>{js.current||(e.preventDefault(),Ls.current())});return()=>{t(),r()}},[]);const{invalidate:Us}=Na(x?.id),$s=(0,fn.useCallback)((e,t,r,a)=>{if(Yr(t,{projectId:e}))return Ge.warn("[save] View-only project: change not saved",{projectId:e,keys:Object.keys(r)}),void Zs(e,Object.keys(r));if(Ge.error("[save] Failed to persist project update",t,{projectId:e,keys:Object.keys(r)}),!Ps.current.some(t=>t.id===e))return;Ae.error(dt("app.changes_not_saved"),{id:`project-save-error-${e}`,description:t instanceof Error&&t.message?t.message:dt("app.check_connection"),duration:1/0,action:{label:dt("action.retry"),onClick:()=>{const t=js.current,s={};for(const a of Object.keys(r))s[a]="tasks"!==a&&"boards"!==a&&"okrs"!==a&&t&&t.id===e?t[a]:r[a];s.lastUpdated=Date.now(),cn(e,s,a).then(()=>Ae.success(dt("app.changes_saved"),{id:`project-save-error-${e}`,duration:3e3})).catch(t=>$s(e,t,r,a))}}})},[]),Fs=(0,fn.useCallback)(async(e,t=!1,r={})=>{const a=js.current,s=r.projectId??a?.id;if(!s)return!1;if(Qr(s))return Ge.warn("[save] View-only project: update dropped",{projectId:s,keys:Object.keys(e)}),Jr(),!1;const{lastUpdated:n,...i}=e,o={...i};if(!a||a.id!==s){const e=vs.current.get(s);if(e||(r.okrsBase||delete o.okrs,delete o.tasks,delete o.boards),0===Object.keys(o).length)return!1;const t={tasks:e?.tasks??[],boards:e?.boards??[],okrs:r.okrsBase??e?.okrs};e&&vs.current.set(s,{...e,...o});const a=e?.name??"your other project";try{return await cn(s,{...o,lastUpdated:Date.now()},t),Ae.info(dt("app.saved_closed_project",{name:a}),{id:`closed-project-save-${s}`}),!0}catch(y){return $s(s,y,o,t),!1}}const l=a,c=aa.current;if(!c&&"name"in o&&(delete o.name,0===Object.keys(o).length))return!1;const d=Date.now(),u=++ys.current;for(const f of Object.keys(o))ws.current.set(`${s}:${f}`,u);c&&o.branding?.name&&o.branding.name!==l.branding?.name?o.name=o.branding.name:c&&o.ideaRaw&&"New Startup"===l.name&&void 0===o.name&&(o.name=o.ideaRaw.slice(0,40));const m=r.okrsBase??l.okrs??{objectives:[]},p=e=>{const t={...e,...o,lastUpdated:d};return o.okrs&&(t.okrs=Ua(m,o.okrs,e.okrs)),t},h=p(l);js.current=h,_(e=>e&&e.id===s?p(e):e),f(e=>e.map(e=>e.id===s?{...e,name:h.name,lastUpdated:d,refinedPitch:h.refinedPitch}:e));const g={tasks:l.tasks,boards:l.boards,okrs:m};let x=!0;try{await cn(s,{...o,lastUpdated:d},g)}catch(y){const e=y instanceof ms?Object.fromEntries(Object.entries(o).filter(([e])=>y.fields.includes(e))):o;x=0===Object.keys(e).length;const{tasks:t,boards:r,...a}=e;void 0===t&&void 0===r||_(e=>{if(!e||e.id!==s)return e;const a={...e};return void 0!==t&&e.tasks===h.tasks&&(a.tasks=l.tasks),void 0!==r&&e.boards===h.boards&&(a.boards=l.boards),a}),Object.keys(a).length>0?$s(s,y,a,g):!x&&Yr(y,{projectId:s})?Ge.warn("[save] View-only project: task changes not saved",{projectId:s}):x||(Ge.error("[save] Failed to persist task changes",y,{projectId:s}),Ae.error(y instanceof Error&&y.message?y.message:"Changes could not be saved â please try again.",{id:`project-save-error-${s}`}))}if(x&&!t){const e=Object.keys(o).find(e=>gu.has(e));if(e){const t=`${s}:${e}`;d-(Rs.current.get(t)??0)>3e5&&(Rs.current.set(t,d),Os(s,"module_updated",{module:e}))}}const b={tasks:"tasks",okrs:"okrs",idea:"idea",ideaRaw:"idea",strategy:"strategy",product:"product",customerDiscovery:"customer_segments",customer_segments:"customer_segments",financials:"financial_model",financial_model:"financial_model",competitors:"competitors",marketResearch:"strategy"},j=Object.keys(o),v=new Set;for(const f of j)b[f]&&v.add(b[f]);for(const f of v)Us(f);return x},[Us,$s]),Ws=(0,fn.useCallback)((e,t=!1,r)=>Fs(e,t,r),[Fs]),Ks=(0,fn.useCallback)(async(e,t)=>{await Fs(e,t)},[Fs]),Hs=(0,fn.useCallback)(async t=>{const r=js.current,a=t.title.trim();if(!r||!a)return!1;const s=t.id??D();if((r.tasks||[]).some(e=>e.id===s))return!0;const n=r.boards?.find(e=>"Main Board"===e.name)??r.boards?.[0],i=Ia(n),o={id:s,boardId:n?.id||"",title:a,description:t.description??"",status:i?Sa(i.type):"TODO",status_id:i?.id,priority:t.priority??"MEDIUM",assignee:"",dueDate:"",createdAt:Date.now(),createdBy:e?.id,progress:0,relatedTaskIds:[],sourceModule:t.sourceModule,sourceTitle:t.sourceTitle};return Fs({tasks:[...r.tasks||[],o]},!0,{projectId:r.id})},[Fs,e?.id]),{notifyPlanningChange:qs,hasExecutionStarted:zs,markExecutionStarted:Vs}=(({state:e,onUpdate:t,activeModule:r,readOnly:a=!1})=>{const[s,n]=(0,fn.useState)([]),i=(0,fn.useRef)(new Set),o=null!=e?.executionStartedAt,l=!0===e?.planningWarningsDismissed,c=(0,fn.useCallback)(t=>{if(!e)return!1;switch(t){case"tasks":return(e.tasks?.length||0)>0;case"financeDashboard":return(e.financials?.length||0)>0||!!e.capTable;case"growth":return(e.growth?.socialPosts?.length||0)>0;case"mentor":return(e.mentorChat?.length||0)>0;case"investorPipeline":return(e.fundraising?.investors?.length||0)>0;case"risk":return(e.risks?.length||0)>0;case"okrs":return(e.milestones?.length||0)>0;default:return!1}},[e]),d=(0,fn.useCallback)(()=>
2{if(!o||l||!r)return null;const e=Lc[r];if(!e)return null;const t=bt.find(t=>t.sourceModule===e);if(!t)return null;const a=t.affectedModules.filter(c);return 0===a.length?null:{sourceModule:e,affectedModules:a,description:t.description}},[r,o,l,c]),u=(0,fn.useCallback)(()=>{const r=e?.id;if(a||!r||i.current.has(r))return;const s=d();if(!s)return;i.current.add(r);const n=s.affectedModules.map(e=>$c[e]).join(", ");Ae.info(dt("crossmodule.impact_title"),{id:`planning-impact-${r}`,description:dt("crossmodule.impact_desc",{description:s.description,modules:n}),duration:1e4,action:{label:dt("crossmodule.dont_remind"),onClick:()=>{t({planningWarningsDismissed:!0},!0,{projectId:r})}}})},[e?.id,d,t,a]),m=(0,fn.useCallback)(async e=>(u(),await t(e),!0),[u,t]),p=(0,fn.useCallback)(()=>{a||!e||e.executionStartedAt||t({executionStartedAt:Date.now()})},[e,t,a]),h=(0,fn.useCallback)(e=>{n(t=>t.filter(t=>t.id!==e))},[]);return{suggestions:s,dismissSuggestion:h,dismissAllSuggestions:(0,fn.useCallback)(()=>{n([])},[]),applySuggestion:(0,fn.useCallback)(async e=>(h(e.id),e),[h]),notifyPlanningChange:u,safeUpdateProject:m,hasExecutionStarted:o,markExecutionStarted:p}})({state:x||ju(),onUpdate:Ws,activeModule:B,readOnly:ta}),[Bs,Gs]=(0,fn.useState)(()=>{try{return"true"===localStorage.getItem("portfolioOnboardingShown")}catch{return!1}});(0,fn.useEffect)(()=>{if(!ra&&!ta&&Cr(B)&&x&&!x.executionStartedAt&&(Vs(),We(!0),!Bs)){Qe(!0),Gs(!0);try{localStorage.setItem("portfolioOnboardingShown","true")}catch{}}},[B,x?.id,x?.executionStartedAt,Vs,Bs,ra,ta]);const{presenceUsers:Ys,updateEditingItem:Js,getUsersEditingItem:Qs}=Hc(x?.id||null,B),an=(0,fn.useCallback)((e,t)=>{const r=js.current;r&&Za(r,{tasks:e,boards:t})&&(_(r=>r?{...r,tasks:e??r.tasks,boards:t??r.boards}:r),Ae.info(dt("app.tasks_updated_teammate"),{description:dt("app.tasks_updated_teammate_desc")}))},[]),sn=(0,fn.useCallback)(()=>js.current,[]);!function(e,t,r){const a=(0,fn.useRef)(t);a.current=t;const s=(0,fn.useRef)(r?.getLocalTasks);s.current=r?.getLocalTasks;const n=r?.userId??null;(0,fn.useEffect)(()=>{if(!e||!Ft())return;let t=!1,r=0;const i=Lt.channel(Jt(`project-tasks-sync:${e}:${n??"anon"}`)).on("postgres_changes",{event:"UPDATE",schema:"public",table:"projects",filter:`id=eq.${e}`},async n=>{const i=++r;if(t)return;const o=n.new;let l=o?.tasks,c=o?.boards,d=o?.tasks_version;if(void 0===l||void 0===c){const{data:t,error:r}=await Lt.from("projects").select("tasks, boards, tasks_version").eq("id",e).maybeSingle();if(r)return void Ge.error("Realtime task sync refetch failed",r,{projectId:e});if(!t)return;l=t.tasks,c=t.boards,d=t.tasks_version}if(!t&&i===r){if(us(e,"number"==typeof d?d:void 0),Array.isArray(l)){const e=s.current?.()?.tasks;l=Va(l,Array.isArray(e)?e:null)}za(e,{tasks:l,boards:c},s.current?.())||a.current(l,c)}});i.subscribe();let o=null,l=null,c=0;const d=()=>{l&&clearTimeout(l),l=setTimeout(async()=>{l=null;const r=++c,n=await Qa(e);if(t||r!==c||!n)return;const i=s.current?.();if(!i||!Array.isArray(i.tasks))return;const o=qa(e,i.tasks,n);o&&a.current(o,i.boards)},150)},u=Ga(()=>{if(t||o)return;const r=`project_id=eq.${e}`;o=Lt.channel(Jt(`project-private-tasks:${e}:${n??"anon"}`)).on("postgres_changes",{event:"INSERT",schema:"public",table:Xa,filter:r},d).on("postgres_changes",{event:"UPDATE",schema:"public",table:Xa,filter:r},d).on("postgres_changes",{event:"DELETE",schema:"public",table:Xa},t=>{const r=t.old?.row_id;"string"==typeof r&&Ya(e,r)&&d()}),o.subscribe()});return()=>{t=!0,u(),l&&clearTimeout(l),Lt.removeChannel(i),o&&Lt.removeChannel(o)}},[e,n])}(x?.id||null,an,{getLocalTasks:sn,userId:e?.id??null});const nn=(0,fn.useCallback)((e,t,r)=>{const a=Is.current;if(!a||a.projectId!==e)return;if(null!==r&&null!==a.version&&r<=a.version)return;if(null===r&&Ja(t,a.okrs))return;const s=a.okrs;Is.current={projectId:e,okrs:t,version:r??a.version},_(r=>{if(!r||r.id!==e)return r;const a=Ua(s,r.okrs,t);return Ja(a,r.okrs)?r:{...r,okrs:a}})},[]);!function(e,t){const r=(0,fn.useRef)(t);r.current=t,(0,fn.useEffect)(()=>{if(!e||!Ft())return;let t=!1,a=null;const s=e=>{null!==e&&(null===a||e>a)&&(a=e)},n=()=>{os(e).then(e=>{t||s(e.version)}).catch(t=>Ge.error("Failed to refresh OKRs",t,{projectId:e}))},i=Lt.channel(Jt(`project-okrs-sync:${e}`)).on("postgres_changes",{event:"UPDATE",schema:"public",table:"projects",filter:`id=eq.${e}`},i=>
2{if(t)return;const o=i.new??{},l="number"==typeof o.okrs_version?o.okrs_version:null;null!==l?null!==a&&l<=a||(s(l),void 0!==o.okrs&&null!==o.okrs?r.current(e,Ca(o.okrs),l):n()):void 0!==o.okrs&&null!==o.okrs&&r.current(e,Ca(o.okrs),null)});return i.subscribe(),n(),()=>{t=!0,Lt.removeChannel(i)}},[e])}(x?.id??null,nn),(0,fn.useEffect)(()=>rs(({projectId:e,okrs:t,version:r})=>nn(e,t,r)),[nn]),(0,fn.useEffect)(()=>{const e=()=>{const e=js.current?.id;e&&os(e).catch(t=>Ge.error("Failed to refresh OKRs after an external update",t,{projectId:e}))};return window.addEventListener("okrs-updated-externally",e),()=>window.removeEventListener("okrs-updated-externally",e)},[]);const{activities:ln,loading:dn}=(e=>{const{user:t}=$t(),[r,a]=(0,fn.useState)([]),[s,n]=(0,fn.useState)(!0),i=(0,fn.useRef)(null);return(0,fn.useEffect)(()=>{if(!e||!t)return;const r=async()=>{n(!0);const{data:r,error:s}=await Lt.from("project_activity_log").select("id, user_id, action, details, created_at, target_type, target_id").eq("project_id",e).neq("user_id",t.id).order("created_at",{ascending:!1}).limit(20);if(s||!r)return void n(!1);const i=[...new Set(r.map(e=>e.user_id))],{data:o}=await Lt.from("profiles").select("user_id, display_name").in("user_id",i),l=new Map((o||[]).map(e=>[e.user_id,e.display_name||"Unknown"])),c=r.map(e=>{const t=e.details;return{id:e.id,userId:e.user_id,userName:l.get(e.user_id)||"Unknown",action:e.action,actionLabel:ld[e.action]||e.action.replace(/_/g," "),targetTitle:null==(t?.title??t?.name)?void 0:String(t?.title??t?.name),targetType:e.target_type||void 0,targetId:e.target_id||void 0,module:null==t?.module?void 0:String(t.module),createdAt:e.created_at}});a(c),n(!1)};r();const s=Lt.channel(Jt(`activity-feed-${e}-${t.id}`)).on("postgres_changes",{event:"INSERT",schema:"public",table:"project_activity_log",filter:`project_id=eq.${e}`},()=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{i.current=null,r()},500)}).subscribe();return()=>{i.current&&(clearTimeout(i.current),i.current=null),Lt.removeChannel(s)}},[e,t]),{activities:r,loading:s}})(x?.id||null),{items:un,toggleStar:mn}=Ns(x?.id||""),pn=(gn=x,(0,fn.useMemo)(()=>{if(!gn)return null;const e=[{id:"ideation",module:jt.IDEATION,completed:!!gn.refinedPitch&&!!gn.problemStatement,title:"Define your startup idea",description:"A clear pitch and problem statement unlock all downstream modules.",impact:"Unlocks Market Research, Strategy, and Pitch Deck",priority:"high"},{id:"market",module:jt.MARKET_RESEARCH,completed:!!gn.marketResearch,title:"Research your market",description:"Understand TAM/SAM/SOM and competitive landscape to validate your idea.",impact:"Improves Strategy and Marketing quality by ~40%",priority:"high",dependsOn:["ideation"]},{id:"customer",module:jt.CUSTOMER_DISCOVERY,completed:!!gn.customerDiscovery,title:"Define customer personas",description:"Map your target customers to refine messaging and product features.",impact:"Sharpens Marketing, Product Vision, and Pitch Deck",priority:"high",dependsOn:["ideation"]},{id:"strategy",module:jt.STRATEGY,completed:!!gn.strategy,title:"Build your business strategy",description:"Define your business model, pricing, and competitive advantage.",impact:"Drives Financial Model and OKR planning",priority:"high",dependsOn:["ideation","market"]},{id:"product",module:jt.PRODUCT,completed:!!gn.product,title:"Define your product vision",description:"Outline features, MVP scope, and technical architecture.",impact:"Enables Roadmap and Task planning",priority:"medium",dependsOn:["strategy"]}
2,{id:"financials",module:jt.FINANCIALS,completed:(gn.financials?.length||0)>0,title:"Create financial projections",description:"Model revenue, costs, and runway to validate your strategy.",impact:"Critical for Fundraising Strategy and Fundraising",priority:"medium",dependsOn:["strategy"]},{id:"marketing",module:jt.MARKETING,completed:!(!gn.marketingStrategy||!gn.branding),title:"Set up Marketing & Branding",description:"Define your brand identity, messaging, and go-to-market channels.",impact:"Powers growth campaigns and pitch materials",priority:"medium",dependsOn:["customer"]},{id:"pitch",module:jt.PITCH_DECK,completed:(gn.pitchDeck?.length||0)>0,title:"Build your Pitch Deck",description:"Create a compelling investor presentation from your planning data.",impact:"Required for fundraising conversations",priority:"medium",dependsOn:["strategy","financials"]},{id:"okrs",module:jt.OKRS,completed:(gn.okrs?.objectives||[]).filter(e=>!e.isArchived).length>0,title:"Set OKRs & Goals",description:"Define objectives and key results to track execution progress.",impact:"Provides weekly rhythm and accountability",priority:"medium",dependsOn:["strategy"]},{id:"tasks",module:jt.TASKS,completed:(gn.tasks||[]).filter(e=>!e.archivedAt).length>=3,title:"Create your first tasks",description:"Break down your next steps into actionable sprint tasks.",impact:"Turns strategy into daily execution",priority:"low",dependsOn:["product"]}],t=!0===gn.toolsOnlyMode;for(const r of e)if(!r.completed&&(!t||!Xt(r.module))&&(t||(r.dependsOn||[]).every(t=>e.find(e=>e.id===t)?.completed)))return{id:r.id,title:r.title,description:r.description,module:r.module,priority:r.priority,impact:r.
2impact};return null},[gn]));var gn;const xn=function(e){const[t,r]=(0,fn.useState)(0),[a,s]=(0,fn.useState)(0),[n,i]=(0,fn.useState)(0),[o,l]=(0,fn.useState)(!0),c=(0,fn.useCallback)(async()=>{if(!e)return r(0),s(0),i(0),void l(!1);try{l(!0);const t=Date.now(),a=new Date(t-12096e5).toISOString(),n=e=>{const t=new Date(e);return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`},o=n(t),c=n(t+6048e5),{data:d,error:u}=await Lt.rpc("crm_deal_signal_counts",{p_project_id:e,p_stale_before:a,p_close_from:o,p_close_to:c});if(!u){const e=d,t=Array.isArray(e)?e[0]??null:e;return r(Number(t?.stale_count)||0),s(Number(t?.closing_count)||0),void i(Number(t?.open_count)||0)}"PGRST202"!==u.code&&Ge.warn("crm_deal_signal_counts failed; using name-based counts",u);const m=`(${ac.map(e=>`"${e}"`).join(",")})`,[p,h,f]=await Promise.all([Lt.from("crm_deals").select("id",{count:"exact",head:!0}).eq("project_id",e).is("deleted_at",null).not("stage","in",m).lt("updated_at",a),Lt.from("crm_deals").select("id",{count:"exact",head:!0}).eq("project_id",e).is("deleted_at",null).not("stage","in",m).gte("expected_close_date",o).lte("expected_close_date",c),Lt.from("crm_deals").select("id",{count:"exact",head:!0}).eq("project_id",e).is("deleted_at",null).not("stage","in",m)]);r(Number(p?.count)||0),s(Number(h?.count)||0),i(Number(f?.count)||0)}catch{r(0),s(0),i(0)}finally{l(!1)}},[e]);(0,fn.useEffect)(()=>{c()},[c]);const d=(0,fn.useRef)(c);return(0,fn.useEffect)(()=>{d.current=c},[c]),(0,fn.useEffect)(()=>{const e=()=>{d.current()};return window.addEventListener("crm-updated-externally",e),()=>window.removeEventListener("crm-updated-externally",e)},[]),{staleDealCount:t,closingThisWeekCount:a,openDealCount:n,loading:o,refresh:c}}(x?.id||null),_n=dd(x,B,{crm:{staleDealCount:xn.staleDealCount,closingThisWeekCount:xn.closingThisWeekCount,openDealCount:xn.openDealCount}});ud(x?.id,_n);const{online:yn,syncStatus:wn,pendingCount:Nn,conflictCount:kn,lastSyncTime:Sn,manualSync:In}=Zc(e?.id),Cn=(0,fn.useCallback)((e,t)=>{if(en(),!ja&&Xt(e)&&Cr(t))return da({from:e,to:t}),void la(!0);Y(t)},[ja]);dr(Y,Cn,B),(0,fn.useEffect)(()=>{wa.activate(B)},[B]);const En=(0,fn.useCallback)(()=>{va(!0);try{localStorage.setItem("transitionCoachDisabled","true")}catch{}Ae.success(dt("app.review_disabled"))},[]),Tn=(0,fn.useCallback)(()=>{ca&&Y(ca.to),la(!1),da(null)},[ca]),An=(0,fn.useCallback)(()=>{la(!1),da(null)},[]),Dn=(0,fn.useCallback)(e=>{R(e),Y(jt.TASKS)},[]),On=(0,fn.useCallback)(e=>{P(e),Y(jt.NOTES)},[]),Rn=(0,fn.useCallback)(e=>{const t=(js.current?.tasks||[]).map(t=>t.id===e?{...t,status:"DONE"}:t);Ws({tasks:t}).then(e=>{e&&Ae.success(dt("app.task_completed"))})},[Ws]),Mn=(0,fn.useMemo)(()=>h.filter(e=>"owned"===Te?!1!==e.isOwner:"shared"!==Te||!0===e.isShared).filter(e=>!Re.trim()||e.name.toLowerCase().includes(Re.trim().toLowerCase())).sort((e,t)=>{switch(Pe){case"newest":return new Date(t.createdAt||0).getTime()-new Date(e.createdAt||0).getTime();case"alphabetical":return e.name.localeCompare(t.name);default:return e.isFavorite&&!t.isFavorite?-1:!e.isFavorite&&t.isFavorite?1:t.lastUpdated-e.lastUpdated}}),[h,Te,Re,Pe]),Pn=(0,fn.useMemo)(()=>{const e=new Map;for(const t of Mn)e.set(t.id,{created:t.createdAt?pe(new Date(t.createdAt),{addSuffix:!0}):"N/A",edited:pe(new Date(t.lastUpdated),{addSuffix:!0})});return e},[Mn]),{overdueTaskCount:Ln,tasksDueTodayCount:Un}=br(x),$n=async(e,t)=>{t?.stopPropagation();const r=h.find(t=>t.id===e);if(!r)return;const a=!r.isFavorite;f(t=>t.map(t=>t.id===e?{...t,isFavorite:a}:t));try{await ls(e,a)}catch{f(t=>t.map(t=>t.id===e?{...t,isFavorite:!a}:t)),Ae.error(dt("app.favorite_failed"))}};(0,fn.useEffect)(()=>{t||e||o(bs(`${window.location.pathname}${window.location.search}`))},[e,t,o]),(0,fn.useEffect)(()=>{document.documentElement.classList.remove("light","dark"),document.documentElement.classList.add(ve)},[ve]),(0,fn.useEffect)(()=>{if(!e)return;if(zr("1tab_theme"))return;(async()=>{const{data:t}=await Lt.from("profiles").select("theme_preference, theme_chosen").eq("user_id",e.id).maybeSingle();t?.theme_chosen&&t.theme_preference&&t.theme_preference!==ve&&(we(t.theme_preference),qr("1tab_theme",t.theme_preference))})()},[e?.id]);const Fn=async()=>{const t="dark"===ve?"light":"dark";if(we(t),qr("1tab_theme",t),e){const{error:r}=await Lt.from("profiles").update({theme_preference:t,theme_chosen:!0}).eq("user_id",e.id);r&&Ge.error("Failed to save theme preference",r)}};(0,fn.useEffect)(()=>
2{if(!e)return;const t=`1tab_projectList_cache_${e.id}`;let r=!1;if(0===h.length){const e=zr(t);if(e)try{const t=JSON.parse(e);Array.isArray(t?.projects)&&t.projects.length>0&&(t.projects.some(e=>"string"==typeof e?.name&&e.name.endsWith("..."))||(f(t.projects),v(!1),r=!0))}catch{}}try{const t=localStorage.getItem(`1tab_lastVisit_${e.id}`);if(t){const e=JSON.parse(t);e?.projectId&&(Or.current={projectId:e.projectId,promise:ns(e.projectId)})}}catch{}(async a=>{a&&v(!0);try{const a=tn(e.id);Ut.mark("index:loadData"),Ut.log(a?"Using preloaded projects promise":"Fetching projects fresh","index:loadData");let i=!1,o=[];try{o=await(a??ds(e.id)),i=!0}catch(s){Ge.error("Failed to load projects:",s)}if(Ut.mark("index:projectsReady"),Ut.log("Projects resolved","index:loadData"),!i&&!r)try{await new Promise(e=>setTimeout(e,1500)),o=await ds(e.id)}catch(n){Ge.error("Retry also failed:",n)}if((o.length>0||!r)&&f(o),e.email&&Gr(e.id,e.email).catch(e=>Ge.error("Failed to link pending invitations:",e)),o.length>0)try{localStorage.setItem(t,JSON.stringify({projects:o,cachedAt:Date.now()}))}catch{}}catch(s){Ge.error("Failed to load projects",s)}finally{v(!1),Ut.mark("index:ready"),Ut.summary()}})(!r)},[e?.id]);const[Wn,Kn]=(0,fn.useState)(()=>Cr(B)?"execution":"planning");(0,fn.useEffect)(()=>{Cr(B)?Kn("execution"):Xt(B)&&Kn("planning")},[B]),(0,fn.useEffect)(()=>{document.title=x?.name?`${x.name} â 1tab.ai`:"1tab.ai"},[x?.name]),(0,fn.useEffect)(()=>{if(B!==jt.DASHBOARD)return;const e=window,t="function"==typeof e.requestIdleCallback,r=t?e.requestIdleCallback.bind(window):e=>window.setTimeout(e,200),a=t?e.cancelIdleCallback.bind(window):e=>window.clearTimeout(e),s=r(()=>{qe(()=>import("./TaskManager-BHlxdUWP.js"),__vite__mapDeps([62,1,2,3,4,5,6,7,8,9,10,11,12,63,64,65,13,14,66,27,50,23,54,67,15,16,17,18,19,20,21,68,26,22,24,25,28,29,30,31,32,33,51,37,35,36,38,39,40,41,42,69,70,71,72,45,73,74,55,75,76,57,77,78,79,80,81,43,44,46,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98])),qe(()=>import("./OKRs-DMr0qGGK.js"),__vite__mapDeps([117,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,54,67,15,16,17,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,51,36,37,42,41,69,70,71,72,45,73,74,55,75,76,57,78,79,80,81,44,46,101,82,110,85,87,118,97,119,88,90,120,121,122,33,100,43,123,124,91,125,116,126,127,96,35,38,39,40,95,94,128])),qe(()=>import("./Notes-D-q6uGpm.js"),__vite__mapDeps([99,1,2,3,4,5,6,7,8,9,10,11,12,13,14,66,27,50,57,54,17,15,16,18,19,20,21,68,26,23,22,24,25,28,29,30,31,32,36,37,45,74,55,75,78,100,43,44,46,101,102,82,103,104,105,106,107,88,108,109,110,111,112,113,51,85,86,94,114,115,91,93,95,116]))});return()=>a(s)},[B]),(0,fn.useEffect)(()=>{Xt(B)?me(B):Cr(B)&&fe(B)},[B]),(0,fn.useEffect)(()=>{if(x&&e)try{const t={projectId:x.id,projectName:x.name,module:B};re(e.id,t)}catch{}},[x?.id,B,e?.id]),(0,fn.useEffect)(()=>{if(!e||j)return;if(Mr.current)return;if(x)return void(Mr.current=!0);const t=dc(c.toString());if(Mr.current=!0,t.projectId||t.settings)return;if(t.skipRestore)return;const r=t.module||((a=t).taskId||a.noteId||a.okrId||a.channel||a.messageId||a.meetingId)?t:null;var a;try{const t=ne(e.id,new Set(h.map(e=>e.id)));if(t){ir(t),w(!0);const e=Es.current;Z.current=t.projectId;const a=()=>{Bn(t.projectId,r?.taskId??void 0,r&&uc(r)||t.module,r?{channel:r.channel,message:r.messageId,note:r.noteId,okr:r.okrId,meeting:r.meetingId}:void 0)};ts().then(s=>{if(Es.current===e&&!js.current)if(s&&s.id===t.projectId){const e=vu(s);Cs(e),_(e),E({projectId:e.id,status:"loading"}),r&&Vn(r)||!t.module||Y(t.module),w(!1),Bn(t.projectId,void 0,void 0,void 0,{silent:!0})}else a()}).catch(()=>a())}}catch(s){Ge.error("Failed to restore last visit:",s)}},[e?.id,j,h.length]);const Hn=async()=>{i(),en(),await on(4e3),await r(),Ae.success(dt("app.signed_out")),o("/auth?signed_out=1")},qn=(0,fn.useCallback)(e=>{e?.replaceHistory&&(ee.current=!0),!1!==e?.flush&&en(),Es.current+=1,As.current=null,w(!1),S(null),_(null)},[]),zn=(0,fn.useCallback)(async(e,t,r)=>{const a=()=>Es.current===t&&js.current?.id===e,s=t=>ks(e,t,r);for(let n=1;n<=3;n++){const t=await ps(e);if(!a())return;
2if(t){const r=js.current;if(!r||r.id!==e)return;const a=vu(_u(r,t,cs,s));return js.current=a,_(r=>r&&r.id===e?vu(_u(r,t,cs,s)):r),E({projectId:e,status:"loaded"}),void Da(a).catch(e=>Ge.error("Failed to cache project to IndexedDB:",e))}n<3&&await new Promise(e=>setTimeout(e,1500*n))}a()&&E({projectId:e,status:"error"})},[ks]),Vn=(0,fn.useCallback)(e=>{const t=uc({projectId:null,module:null,taskId:null,noteId:null,okrId:null,channel:null,messageId:null,meetingId:null,settings:null,skipRestore:!1,...e});return t&&Y(t),e.taskId&&R(e.taskId),e.noteId&&P(e.noteId),e.channel&&U(e.channel),e.messageId&&F(e.messageId),e.meetingId&&K(e.meetingId),e.okrId&&yt({open:!0,type:"okr",id:e.okrId}),t},[]),Bn=(0,fn.useCallback)(async(e,t,r,a,s)=>{const i=!!s?.silent,o=++Es.current,l=ys.current;js.current?.id!==e&&(en(),E({projectId:e,status:"loading"})),i||(Ts.current=o,As.current=e,w(!0)),performance.now();try{let s=null;if(Or.current?.projectId===e){let t=!1;const r=Or.current.promise.finally(()=>{t=!0});Or.current=null;const a=new Promise(r=>{setTimeout(()=>{t?r(null):ns(e).then(r).catch(()=>r(null))},500)});s=await Promise.race([r,a])}else s=await ns(e);if(Es.current!==o)return!1;if(i&&js.current?.id!==e)return!1;if(s){const c=vu(s);if(js.current?.id===e){const t=hs.filter(e=>"okrs"!==e),r=t=>ks(e,t,l);_(a=>a&&a.id===e?_u(a,c,t,r):a),Is.current?.projectId===e&&null===Is.current.version&&nn(e,c.okrs??{objectives:[]},null)}else Cs(c),js.current=c,_(c);return i||(Vn({module:ic(r),taskId:t??null,channel:a?.channel??null,messageId:a?.message??null,noteId:a?.note??null,okrId:a?.okr??null,meetingId:a?.meeting??null})||Y(c.toolsOnlyMode?jt.TASKS:jt.IDEATION),n("project_opened","dashboard",e)),zn(e,o,l),!0}return i?js.current?.id===e&&E({projectId:e,status:"error"}):Ae.error(dt("app.project_load_failed")),!1}catch(c){return Ge.error("Failed to open project",c),i||Ae.error(dt("app.project_load_failed")),!1}finally{i||Ts.current!==o||(As.current=null,w(!1),S(null))}},[n,ks,nn,Cs,zn,Vn]),Gn=(0,fn.useCallback)(()=>{const e=js.current?.id;e&&(E({projectId:e,status:"loading"}),Bn(e,void 0,void 0,void 0,{silent:!0}))},[Bn]);(0,fn.useEffect)(()=>{const e=e=>{const t=e.detail;if(!t?.projectId||js.current?.id!==t.projectId)return;const{projectId:r,fields:a}=t,s=ys.current,n=a.filter(e=>cs.includes(e)),i=a.filter(e=>hs.includes(e)&&"tasks"!==e&&"boards"!==e&&"okrs"!==e);0===i.length&&0===n.length||Promise.all([n.length>0?ps(r):Promise.resolve(null),i.length>0?ns(r):Promise.resolve(null)]).then(([e,t])=>{if(!e&&!t||js.current?.id!==r)return;const a=e=>ks(r,e,s);_(s=>{if(!s||s.id!==r)return s;let o=s;return e&&(o=_u(o,e,n,a)),t&&(o=_u(o,t,i,a)),vu(o)}),t&&i.includes("name")&&!a("name")&&f(e=>e.map(e=>e.id===r?{...e,name:t.name}:e))}).catch(e=>Ge.error("Failed to refresh project fields",e,{projectId:r}))};return window.addEventListener(Xs,e),()=>window.removeEventListener(Xs,e)},[ks]);const Yn=x?.id??null,Jn=e?.id??null;(0,fn.useEffect)(()=>{const e=Yn;if(!e||!Jn)return;let t=!1;return es(Jn,e).then(r=>{if(t||!r||"pending"!==r.status)return;if(js.current?.id!==e||Qr(e))return;const a=r.patch.fields,s=Object.keys(a);if(0===s.length)return;const n=++ys.current;s.forEach(t=>ws.current.set(`${e}:${t}`,n)),_(t=>t&&t.id===e?vu({...t,...a}):t)}).catch(t=>Ge.warn("Could not read queued offline edits for the open project",t,{projectId:e})),()=>{t=!0}},[Yn,Jn]),(0,fn.useEffect)(()=>{const e=e=>{en(),hn()&&(e.preventDefault(),e.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[]);const Qn=(0,fn.useCallback)(()=>{if(As.current)return;const{pathname:e,search:t}=window.location,r=js.current?.id??null,a=Q.current,s=Z.current,n=ee.current;Z.current=null,ee.current=!1;const i=mc(t,r,a);if("none"===i)return;const l="replace"===i||n||!!r&&s===r;o({pathname:e,search:pc(t,r,a)},{replace:l})},[o]),Zn=(0,fn.useCallback)((e,t)=>{const r=dc(e);if(r.settings)return void o((a=r.settings,`/profile?section=${hc[a.trim().toLowerCase()]??"profile"}`),{replace:!0});var a;const s=js.current,n=uc(r),i={channel:r.channel,message:r.messageId,note:r.noteId,okr:r.okrId,meeting:r.meetingId};if(r.projectId&&r.projectId!==s?.id){if(As.current===r.projectId)return;return void Bn(r.projectId,r.taskId??void 0,n??void 0,i).then(e=>{e||dc(window.location.search).projectId!==r.projectId||(ee.current=!0,Qn())})}if(!r.projectId&&!n)return void(t||!s&&!As.current?s||Qn():qn());if(!s)return;As.current&&As.current!==s.id&&(Es.current+=1,As.current=null,w(!1),S(null),E({projectId:s.id,status:"loading"}),Bn(s.id,void 0,void 0,void 0,{silent:!0}));const l=Vn({...r,module:n});l&&l!==Q.current||Qn()},[o,Bn,qn,Vn,Qn]),Xn=(0,fn.useRef)(null);(0,fn.useEffect)(()=>
2{if(e&&!j){if(Xn.current!==u.key){const e=null===Xn.current;return Xn.current=u.key,void Zn(u.search,e)}Qn()}},[e,j,u.key,u.search,x?.id,B,Zn,Qn]),(0,fn.useEffect)(()=>{if("1"!==c.get("modules"))return;if(!x)return;Qt(!0);const e=new URLSearchParams(window.location.search);e.delete("modules");const t=e.toString();o({pathname:window.location.pathname,search:t?`?${t}`:""},{replace:!0})},[c,x,o]);const{startTutorial:ei,setDashboardEmpty:ti,hasSeenTutorial:ri,dontShowAgain:ai,isTutorialEnabled:si,loading:ni,registerNavigateToProject:ii,registerNavigateToDashboard:oi,registerNavigateToModule:li}=Dr(),ci=(0,fn.useRef)(!1);if((0,fn.useEffect)(()=>{if(t||j||ni)return;if(!e||h.length>0)return;if(ri||ai||!si)return;if(ci.current)return;ci.current=!0;const r=setTimeout(()=>ei(),800);return()=>clearTimeout(r)},[e,t,j,ni,h.length,ri,ai,si,ei]),(0,fn.useEffect)(()=>{if(!j)return ti(0===h.length),()=>ti(!1)},[j,h.length,ti]),(0,fn.useEffect)(()=>{ii(e=>{Bn("pulsehr"===e||"aaaa1111-bbbb-4222-9ccc-dddd33334444"===e?Rr:e)}),oi(()=>{qn()}),li(e=>{te(e)})},[ii,oi,li,Bn,te,qn]),(0,fn.useEffect)(()=>{const e=e=>{const{module:t,section:r,channel:a,meetingId:s,importIntent:n,taskId:i,okrId:o,messageId:l}=e.detail;te(t),i&&R(i),o&&yt({open:!0,type:"okr",id:o}),l&&F(l),t&&n&&z({module:t,intent:n}),t===jt.COMMUNICATION&&a&&U(a),t===jt.MEETINGS&&s&&K(s),t===jt.NOTES&&r&&P(r)};return window.addEventListener("navigate-to-module",e),()=>{window.removeEventListener("navigate-to-module",e)}},[te]),function({currentProjectRef:e,directUpdateProject:t,setCurrentProject:r}){(0,fn.useEffect)(()=>{const a=a=>{const s=a.detail;if(!s)return;const{projectId:n,tasks:i,boards:o,persisted:l}=s;if(!n||!Array.isArray(i)||0===i.length)return;const c=e.current;c&&c.id===n&&(l?r(e=>e&&e.id===n?{...e,tasks:qc(e.tasks||[],i),boards:Array.isArray(o)&&o.length>0?qc(e.boards||[],o):e.boards}:e):t({tasks:qc(c.tasks||[],i)},!0))};return window.addEventListener("project-tasks-upserted",a),()=>window.removeEventListener("project-tasks-upserted",a)},[e,t,r]),(0,fn.useEffect)(()=>{const t=t=>{const a=t.detail;if(!a)return;const{projectId:s,tasks:n,boards:i}=a,o=e.current;o&&o.id===s&&(r(e=>e&&e.id===s?{...e,tasks:n||[],boards:i||[],lastUpdated:Date.now()}:e),Ae.info(dt("tasks.reloaded_remote")))};return window.addEventListener("project-tasks-reconciled",t),()=>window.removeEventListener("project-tasks-reconciled",t)},[e,r])}({currentProjectRef:js,directUpdateProject:Ks,setCurrentProject:_}),t||j)return(0,jn.jsxs)("div",{className:"min-h-screen bg-background flex flex-col items-center justify-center gap-4",children:[(0,jn.jsx)("img",{src:et,alt:"1tab.ai",className:"w-14 h-14 rounded-2xl object-contain"}),(0,jn.jsx)(ce,{className:"w-8 h-8 animate-spin text-primary"}),(0,jn.jsxs)("div",{className:"text-center",children:[(0,jn.jsx)("p",{className:"text-sm text-muted-foreground",children:t?"Authenticating...":"Loading your projects..."}),(0,jn.jsx)("p",{className:"text-xs text-muted-foreground/60 mt-1",children:"Your AI startup operating system"})]})]});if(!e)return null;const di=async()=>{if(!Aa("create a project"))return;if(Ea)return void Ae.info(dt("app.loading_subscription"));const e=h.filter(e=>e.isOwner).length;ka(e)?rt(!0):Ta()};Ls.current=di;const ui=async t=>{if(Ms.current)return;const r=h.filter(e=>e.isOwner).length;if(!Ea&&!ka(r))return rt(!1),void Ta();Ms.current=!0,rt(!1);const s=ju();if(s.onboardingContext={...t,completedAt:Date.now()},t.geo?.scope&&(s.targetGeo=t.geo),t.websiteUrl&&(s.websiteUrl=t.websiteUrl),"have_idea"===t.path&&t.ideaDescription){s.ideaRaw=t.ideaDescription;const e=t.ideaDescription.split(" ").slice(0,4).join(" ");s.name=e.length>40?e.slice(0,40):e}"tools_only"===t.path&&(s.toolsOnlyMode=!0,s.executionStartedAt=Date.now(),s.name=t.workspaceName||"Workspace"),en(),S("tools_only"===t.path?"Creating your workspaceâ¦":"Creating your projectâ¦"),w(!0);try{await is(s)}catch(n){return w(!1),S(null),(e=>{const t=e;return"project_limit_reached"===t?.hint||/project limit reached/i.test(t?.message??"")})(n)?void Ta():(Ge.error("Failed to save new project",n),void Ae.error(dt("app.project_create_failed"),{description:dt("app.check_connection"),duration:15e3,action:{label:dt("action.retry"),onClick:()=>{ui(t)}}}))}finally{Ms.current=!1}Es.current+=1,f(t=>[...t,{id:s.id,name:s.name,lastUpdated:s.lastUpdated,createdAt:s.createdAt,userId:e.id,refinedPitch:s.refinedPitch,isOwner:!0}]),Cs(s),js.current=s,_(s),E({projectId:s.id,status:"loaded"}),"tools_only"===t.path?Y(jt.TASKS):Y(jt.IDEATION),w(!1),S(null),Os(s.id,"project_created"),t.wantsImport&&(nt(s.id),lt(!0)),a("project_created",s.id),"tools_only"===t.path&&Ae.success(dt("app.workspace_created"))},mi=x?.id??null,pi=async(e,t)=>
2!!mi&&(Xt(B)&&zs&&js.current?.id===mi&&qs(),Fs(e,!1,{...t,projectId:mi})),hi=()=>{if(Se.trim()){const e={name:Se};x?.branding&&(e.branding={...x.branding,name:Se}),pi(e)}ke(!1)},fi=(e,t)=>{t.stopPropagation(),$e(e)},gi=async()=>{if(!Ue||!e)return;const t=h.find(e=>e.id===Ue);a("project_deleted",Ue);const r=h.filter(e=>e.id!==Ue);f(r),x?.id===Ue&&qn({flush:!1,replaceHistory:!0}),Mr.current=!0;try{localStorage.removeItem(`1tab_lastVisit_${e.id}`)}catch{}try{await as(Ue,e.id),Ae.success(t?.name?`Deleted "${t.name}"`:"Project deleted")}catch(s){return Ge.error("Error deleting project:",s),Ae.error(dt("app.project_delete_failed")),f(h),void $e(null)}$e(null);try{localStorage.setItem(`1tab_projectList_cache_${e.id}`,JSON.stringify({projects:r,cachedAt:Date.now()}))}catch{}},xi=(e,t)=>{_e(r=>({...r,[e]:t}))},_i=Ds.map(e=>({id:e.id,label:e.label,icon:e.icon})),bi=B===jt.GAME,ji=!bi&&"execution"===Wn,vi=vr,yi=mr;return x?(0,jn.jsx)(Tr,{reducedMotion:"user",children:(0,jn.jsx)(fn.Suspense,{fallback:null,children:(0,jn.jsx)(ot,{language:x.language||st(),children:(0,jn.jsxs)("div",{className:"app-accessible-theme min-h-screen bg-background text-foreground flex flex-col selection:bg-primary/30 transition-colors duration-300 overflow-x-hidden",children:[(0,jn.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-[1200] focus:rounded-md focus:bg-background focus:px-4 focus:py-3 focus:text-foreground focus:shadow-lg focus:outline-none focus:ring-2 focus:ring-ring",children:"Skip to main content"}),(0,jn.jsx)("header",{className:He("sticky top-0 z-50 bg-background/95 backdrop-blur-xl border-b border-border shadow-sm",m?"lg:pl-14":"lg:pl-64"),children:(0,jn.jsx)("div",{className:"max-w-7xl mx-auto px-2 sm:px-4 lg:px-8",children:(0,jn.jsxs)("div",{className:"flex items-center justify-between gap-1 h-14 lg:h-16",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 lg:gap-4 min-w-0 flex-shrink-0",children:[(0,jn.jsx)("button",{onClick:()=>qn(),className:"p-2 hover:bg-muted rounded-lg text-muted-foreground hover:text-foreground transition-colors shrink-0",title:"Back to Dashboard","aria-label":"Back to dashboard",children:(0,jn.jsx)(I,{className:"w-5 h-5"})}),(0,jn.jsxs)("div",{className:"hidden lg:flex flex-col min-w-0",children:[ea.canManageProject?(0,jn.jsx)("div",{className:"flex items-center gap-2 group cursor-pointer",onClick:()=>{Ce(x.name),ke(!0)},children:Ne?(0,jn.jsx)("input",{autoFocus:!0,value:Se,onChange:e=>Ce(e.target.value),onBlur:hi,onKeyDown:e=>"Enter"===e.key&&hi(),className:"bg-muted border border-border rounded px-2 py-0.5 text-sm font-bold focus:ring-2 focus:ring-ring outline-none w-28 lg:w-48"}):(0,jn.jsxs)(jn.Fragment,{children:[(0,jn.jsx)("h2",{className:"font-bold leading-tight max-w-[200px] lg:max-w-md text-sm lg:text-base break-words",title:x.name,children:x.name}),(0,jn.jsx)(Oe,{className:"w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]})}):(0,jn.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,jn.jsx)("h2",{className:"font-bold leading-tight max-w-[200px] lg:max-w-md text-sm lg:text-base break-words",title:x.name,children:x.name}),ta&&(0,jn.jsx)(vn,{})]}),(0,jn.jsx)("div",{className:"hidden lg:flex items-center gap-2",children:(0,jn.jsx)(du,{projectName:x.name,activeModule:B,onNavigateToModule:Y,onBackToDashboard:()=>qn()})})]})]}),!x.toolsOnlyMode&&(0,jn.jsxs)("div",{className:"lg:hidden flex items-center justify-center flex-1 min-w-0 px-1",children:[(0,jn.jsxs)("div",{className:"flex max-w-full items-center bg-muted/50 rounded-full p-1",children:[(0,jn.jsxs)("button",{onClick:()=>{Y(ue)},className:"flex min-w-0 items-center gap-1 px-2 sm:px-3 py-1.5 rounded-full text-[11px] font-bold transition-all "+(ji||bi?"text-muted-foreground":"bg-primary text-primary-foreground"),children:[(0,jn.jsx)(Ie,{className:"w-3.5 h-3.5 shrink-0"}),(0,jn.jsx)("span",{className:"hidden min-[340px]:inline",children:"Plan"})]}),(0,jn.jsxs)("button",{onClick:()=>Y(he),className:"flex min-w-0 items-center gap-1 px-2 sm:px-3 py-1.5 rounded-full text-[11px] font-bold transition-all "+(ji?"bg-success text-success-foreground":"text-muted-foreground"),children:[(0,jn.jsx)(b,{className:"w-3.5 h-3.5 shrink-0"}),(0,jn.jsx)("span",{className:"hidden min-[340px]:inline",children:"Exec"})]}),x.approvedModules?.includes(jt.GAME)&&(0,jn.jsxs)("button",{onClick:()=>Y(jt.GAME),className:"flex min-w-0 items-center gap-1 px-2 sm:px-3 py-1.5 rounded-full text-[11px] font-bold transition-all "+(bi?"bg-ai text-ai-foreground":"text-muted-foreground"),children:[(0,jn.jsx)(X,{className:"w-3.5 h-3.5 shrink-0"}),(0,jn.jsx)("span",{className:"hidden min-[340px]:inline",children:"Game"})]})]}),x.executionStartedAt&&(0,jn.jsx)("div",{className:"w-1.5 h-1.5 rounded-full bg-success animate-pulse ml-1 shrink-0"})]}),!x.toolsOnlyMode&&(0,jn.jsx)("div",{className:"hidden lg:flex items-center flex-1 justify-center",children:(0,jn.jsxs)("div",{"data-tutorial":"phase-switch",className:"flex items-center bg-muted/60 rounded-xl p-1 border border-border/50 gap-1",children:[(0,jn.jsxs)("button",{onClick:()=>{Y(ue)},className:He("flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",ji||bi?"text-muted-foreground hover:text-foreground hover:bg-muted":"bg-primary text-primary-foreground shadow-md"),children:[(0,jn.jsx)(Ie,{className:"w-4 h-4"}),(0,jn.jsx)("span",{children:"Planning"}),(0,jn.jsxs)("span",{className:He("text-xs px-1.5 py-0.5 rounded-full font-mono",ji||bi?"bg-muted":"bg-white/20"),children:[yi(x),"%"]})]}),(0,jn.jsxs)("button",{onClick:()=>Y(he),className:He("flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",ji?"bg-success text-success-foreground shadow-md":"text-muted-foreground hover:text-foreground hover:bg-muted"),children:[(0,jn.jsx)(b,{className:"w-4 h-4"}),(0,jn.jsx)("span",{children:"Execution"}),x.executionStartedAt&&(0,jn.jsx)("div",{className:"w-2 h-2 rounded-full bg-success-strong animate-pulse"})]}),x.approvedModules?.includes(jt.GAME)&&(0,jn.jsxs)("button",{onClick:()=>Y(jt.GAME),className:He("flex items-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",bi?"bg-ai text-ai-foreground shadow-md":"text-muted-foreground hover:text-foreground hover:bg-muted"),children:[(0,jn.jsx)(X,{className:"w-4 h-4"}),(0,jn.jsx)("span",{children:"Game"})]})]})}),x.toolsOnlyMode&&(0,jn.jsx)("div",{className:"hidden lg:flex flex-1"}),(0,jn.jsxs)("div",{className:"flex items-center justify-end gap-1 lg:gap-3 flex-shrink-0",children:[ta&&(0,jn.jsx)(vn,{className:"lg:hidden",compact:!0}),(0,jn.jsx)(fn.Suspense,{fallback:null,children:(0,jn.jsx)(uu,{projectId:x.id})}),(0,jn.jsx)(rn,{variant:"app",className:"hidden lg:inline-flex"}),(0,jn.jsxs)("div",{className:"hidden xl:flex items-center gap-2",children:[(0,jn.jsx)(Ye,{variant:"ghost",size:"icon",className:"h-9 w-9",title:"Search (Cmd+K)","aria-label":"Search",onClick:()=>window.dispatchEvent(new Event("open-command-palette")),children:(0,jn.jsx)(k,{className:"w-5 h-5"})}),!x.toolsOnlyMode&&yi(x)>=100&&(0,jn.jsxs)(Ye,{variant:"ghost",className:"h-9 px-3 hover:bg-muted transition-colors gap-2",onClick:()=>ft(!0),children:[(0,jn.jsx)(d,{className:"w-4 h-4"}),(0,jn.jsx)("span",{className:"text-sm font-medium",children:"Business Plan"})]}),(0,jn.jsx)(au,{projectId:x.id,projectName:x.name,ownerId:x.userId||e?.
2id||"",state:x,isFavorite:h.find(e=>e.id===x.id)?.isFavorite,onToggleFavorite:()=>{$n(x.id)},onDeleteProject:()=>$e(x.id),onProjectRenamed:e=>{_(t=>t?{...t,name:e}:t),f(t=>t.map(t=>t.id===x.id?{...t,name:e}:t))},onUpdate:pi,trigger:(0,jn.jsxs)(Ye,{variant:"ghost",className:"h-9 px-3 hover:bg-muted transition-colors gap-2",title:"Project Settings",children:[(0,jn.jsx)(s,{className:"w-4 h-4"}),(0,jn.jsx)("span",{className:"text-sm font-medium",children:"Settings"})]})}),(0,jn.jsx)(kc,{theme:ve,onToggleTheme:Fn,onLogout:Hn,showExtras:!0,presenceCount:Ys.length,onOpenWallet:()=>{document.querySelector("[data-wallet-trigger]")?.click()},onOpenNews:()=>{document.querySelector("[data-news-trigger]")?.click()}}),(0,jn.jsxs)("div",{className:"hidden",children:[(0,jn.jsx)(Bc,{children:(0,jn.jsx)("button",{"data-wallet-trigger":!0})}),(0,jn.jsx)(Vd,{trigger:(0,jn.jsx)("button",{"data-news-trigger":!0})}),(0,jn.jsx)(iu,{presenceUsers:Ys,activityFeed:ln,activityLoading:dn,onNavigateToModule:e=>Y(e)})]})]}),(0,jn.jsxs)("div",{className:"flex xl:hidden items-center",children:[(0,jn.jsx)(Zd,{theme:ve,onToggleTheme:Fn,onLogout:Hn,businessPlanAvailable:!x.toolsOnlyMode&&yi(x)>=100,onOpenBusinessPlan:()=>ft(!0)}),(0,jn.jsx)("div",{className:"hidden",children:(0,jn.jsx)(au,{projectId:x.id,projectName:x.name,ownerId:x.userId||e?.id||"",state:x,isFavorite:h.find(e=>e.id===x.id)?.isFavorite,onToggleFavorite:()=>{$n(x.id)},onDeleteProject:()=>$e(x.id),onProjectRenamed:e=>{_(t=>t?{...t,name:e}:t),f(t=>t.map(t=>t.id===x.id?{...t,name:e}:t))},onUpdate:pi,listenForOpenEvents:!0})})]})]})]})})}),!1===Oa&&(0,jn.jsx)(od,{onResend:La,resending:$a}),(0,jn.jsx)("div",{className:"max-w-[1920px] mx-auto w-full px-2 sm:px-4 lg:pl-0 lg:pr-8 2xl:pl-0 2xl:pr-12 mt-1 space-y-3",children:(0,jn.jsx)(zd,{})}),(0,jn.jsx)(id,{open:Ra,onOpenChange:Ma,onResend:La,resending:$a,actionDescription:Pa}),(0,jn.jsx)(Xd,{state:x,externalOpen:ht,onExternalOpenChange:ft}),(0,jn.jsxs)("main",{id:"main-content",tabIndex:-1,className:"flex-1 max-w-[1920px] mx-auto w-full relative "+(B===jt.WHITEBOARD?"px-0 py-0 pb-0":l&&B===jt.COMMUNICATION?"px-0 py-0 pb-0 overflow-hidden":[jt.COMMUNICATION,jt.TASKS,jt.NOTES,jt.DRIVE,jt.OKRS,jt.FINANCE_DASHBOARD,jt.INVESTOR_PIPELINE,jt.CRM,jt.MAIL,jt.HR,jt.COMPETITOR_WAR_ROOM,jt.RISK,jt.MENTOR,jt.MEETINGS,jt.GROWTH,jt.DASHBOARD,jt.IDEATION,jt.CUSTOMER_DISCOVERY,jt.MARKET_RESEARCH,jt.STRATEGY,jt.PRODUCT,jt.MARKETING,jt.FINANCIALS,jt.LEGAL,jt.TEAM,jt.PITCH_DECK,jt.FUNDRAISING,jt.WEBSITE,jt.PRICING].includes(B)?"px-0 py-4 pb-32 xl:pb-8 xl:py-0":"px-2 sm:px-4 lg:pl-0 lg:pr-8 2xl:pl-0 2xl:pr-12 py-4 pb-32 xl:pb-8 xl:py-0"),children:[(0,jn.jsx)(gr,{activeModule:B,setActiveModule:Y,onModuleTransition:Cn,currentProject:x,moduleLoading:ge,totalUnreadCount:Pr,tasksHasNew:Fa,notesHasNew:Wa,whiteboardHasNew:Ka,mailVisible:Kr||Hr,activePhase:bi||ji?"execution":"planning",favoriteModules:ie,recentModules:oe,onToggleModuleFavorite:de,onUpgradeToStartup:ta?void 0:async()=>{await Fs({toolsOnlyMode:!1},!0,{projectId:x.id})&&(Y(jt.IDEATION),Ae.success(dt("app.upgraded_full_mode")))}}),(0,jn.jsxs)("div",{className:He(m?"lg:pl-14":"lg:pl-64"),children:[(0,jn.jsx)(Bd,{activeTab:Vt,onTabChange:e=>{en(),"calendar"===e?x&&Y(jt.CALENDAR):"modules"===e?Qt(!0):"tasks"===e?x&&Y(jt.TASKS):"chat"===e?x&&Y(jt.COMMUNICATION):"profile"===e?o("/profile"):"goals"===e?x&&Y(jt.OKRS):"whiteboard"===e?x&&Y(jt.WHITEBOARD):"notes"===e&&x&&Y(jt.NOTES),Gt(e)},unreadChatCount:Pr,tasksOverdue:Ln,tasksDueToday:Un,toolsOnlyMode:x.toolsOnlyMode,activeModule:B,insideProject:!0,projectInitial:(x.name||"P").charAt(0).toUpperCase()}),(0,jn.jsx)(Gd,{open:Yt,onOpenChange:Qt,activeModule:B,onModuleSelect:e=>{Y(e),Gt("modules")},currentProject:x,planningCompletion:yi(x),toolsOnlyMode:x.toolsOnlyMode,favoriteModules:ie,recentModules:oe,onToggleModuleFavorite:de}),x&&un&&un.length>0&&(0,jn.jsx)(pu,{items:un,onItemClick:e=>{"task"===e.item_type?(R(e.item_id),Y(jt.TASKS)):"note"===e.item_type?(P(e.item_id),Y(jt.NOTES)):"okr"===e.item_type?Y(jt.OKRS):"channel"===e.item_type&&Y(jt.COMMUNICATION)},onRemove:e=>mn(e.item_type,e.item_id,e.item_title)}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0 relative bg-card rounded-xl border border-border overflow-hidden "+(l&&B===jt.COMMUNICATION?"h-[calc(100dvh_-_var(--app-header-h)_-_var(--mobile-bottom-nav-h))]":"min-h-[calc(100dvh_-_var(--app-header-h))] overflow-y-auto"),children:[B!==jt.DASHBOARD&&B!==jt.COMMUNICATION&&B!==jt.WHITEBOARD&&B!==jt.NOTES&&(0,jn.jsx)(cu,{activeModule:B,previousModule:_s,hasExecutionStarted:zs,projectId:x.id}),pn&&(0,jn.jsx)("div",{className:B===jt.DASHBOARD?"px-4 pt-2":"hidden",children:(0,jn.jsx)(hu,{action:pn,projectId:x.id,onNavigate:e=>Y(e)},`${x.id}:${pn.id}`)}
2),(0,jn.jsx)(ar,{isViewOnly:ta,reason:"viewer",children:(0,jn.jsx)(xc,{activeModule:B,wrapActiveModule:(e,t)=>(0,jn.jsx)(Er.div,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{duration:.2,ease:"easeOut"},children:e},t),blocked:ia,blockedReason:na?"restricted":"disabled",templateEnabled:Hr,onBack:()=>Y(jt.DASHBOARD),renderers:(e=>{if(T)return e;const t={...e};for(const r of xu)t[r]&&(t[r]=()=>(0,jn.jsx)(bu,{failed:A,onRetry:Gn}));return t})({[jt.IDEATION]:()=>(0,jn.jsx)(fc,{module:jt.IDEATION,children:(0,jn.jsx)(Je,{module:"Ideation",projectId:x.id,children:(0,jn.jsx)(gd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.IDEATION,jt.MARKET_RESEARCH),onLoading:e=>xi(jt.IDEATION,e),initialOpenCoach:Ze,onInitialOpenCoachHandled:()=>Xe(!1)})})}),[jt.NOTES]:()=>(0,jn.jsx)(fc,{module:jt.NOTES,children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(Sr,{}),children:(0,jn.jsx)(Je,{module:"Notes",projectId:x.id,children:(0,jn.jsx)(hd,{projectId:x.id,openNoteId:M,onNoteOpened:()=>P(null),smartAction:wt,onSmartActionHandled:()=>Nt(null),onSelectionChange:St,selectionText:kt})})})}),[jt.CUSTOMER_DISCOVERY]:()=>(0,jn.jsx)(fc,{module:jt.CUSTOMER_DISCOVERY,children:(0,jn.jsx)(Je,{module:"Customer Discovery",projectId:x.id,children:(0,jn.jsx)(Md,{state:x,onUpdate:pi,onNext:()=>Cn(jt.CUSTOMER_DISCOVERY,jt.STRATEGY)})})}),[jt.MARKET_RESEARCH]:()=>(0,jn.jsx)(fc,{module:jt.MARKET_RESEARCH,children:(0,jn.jsx)(Je,{module:"Market Research",projectId:x.id,children:(0,jn.jsx)(xd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.MARKET_RESEARCH,jt.CUSTOMER_DISCOVERY),onLoading:e=>xi(jt.MARKET_RESEARCH,e)})})}),[jt.STRATEGY]:()=>(0,jn.jsx)(fc,{module:jt.STRATEGY,children:(0,jn.jsx)(Je,{module:"Business Strategy",projectId:x.id,children:(0,jn.jsx)(_d,{state:x,onUpdate:pi,onNext:()=>Cn(jt.STRATEGY,jt.PRODUCT),onLoading:e=>xi(jt.STRATEGY,e),deferredLoaded:T})})}),[jt.PRODUCT]:()=>(0,jn.jsx)(fc,{module:jt.PRODUCT,children:(0,jn.jsx)(Je,{module:"Product Vision",projectId:x.id,children:(0,jn.jsx)(bd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.PRODUCT,jt.TEAM),deferredLoaded:T})})}),[jt.TEAM]:()=>(0,jn.jsx)(fc,{module:jt.TEAM,children:(0,jn.jsx)(Je,{module:"Team Planning",projectId:x.id,children:(0,jn.jsx)(Cd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.TEAM,jt.MARKETING),deferredLoaded:T})})}),[jt.MARKETING]:()=>(0,jn.jsx)(fc,{module:jt.MARKETING,children:(0,jn.jsx)(Je,{module:"Marketing",projectId:x.id,children:(0,jn.jsx)(jd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.MARKETING,jt.FINANCIALS),onLoading:e=>xi(jt.MARKETING,e),deferredLoaded:T})})}),[jt.FINANCIALS]:()=>
2(0,jn.jsx)(fc,{module:jt.FINANCIALS,children:(0,jn.jsx)(Je,{module:"Financial Plan",projectId:x.id,children:(0,jn.jsx)(vd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.FINANCIALS,jt.LEGAL),deferredLoaded:T})})}),[jt.LEGAL]:()=>(0,jn.jsx)(fc,{module:jt.LEGAL,children:(0,jn.jsx)(Je,{module:"Legal",projectId:x.id,children:(0,jn.jsx)(Id,{state:x,onUpdate:pi,onNext:()=>Cn(jt.LEGAL,jt.PITCH_DECK)})})}),[jt.PITCH_DECK]:()=>(0,jn.jsx)(fc,{module:jt.PITCH_DECK,children:(0,jn.jsx)(Je,{module:"Pitch Deck",projectId:x.id,children:(0,jn.jsx)(Td,{state:x,onUpdate:pi,onNext:()=>Cn(jt.PITCH_DECK,jt.FUNDRAISING),deferredLoaded:T})})}),[jt.FUNDRAISING]:()=>(0,jn.jsx)(fc,{module:jt.FUNDRAISING,children:(0,jn.jsx)(Je,{module:"Fundraising",projectId:x.id,children:(0,jn.jsx)(Ed,{state:x,onUpdate:pi,onNext:()=>Cn(jt.FUNDRAISING,jt.WEBSITE),deferredLoaded:T})})}),[jt.WEBSITE]:()=>(0,jn.jsx)(fc,{module:jt.WEBSITE,children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(Nr,{}),children:(0,jn.jsx)(Je,{module:"Website",projectId:x.id,children:(0,jn.jsx)(Jd,{state:x,onUpdate:pi,onNext:()=>Cn(jt.WEBSITE,jt.OKRS)})})})}),[jt.DASHBOARD]:()=>(0,jn.jsx)(fc,{module:jt.DASHBOARD,children:(0,jn.jsx)(Je,{module:"Dashboard",projectId:x.id,children:(0,jn.jsx)(su,{currentProject:x,onNavigateToModule:Y,onOpenTask:Dn,onOpenNote:On,onCompleteTask:Rn,hasExecutionStarted:zs,isModuleCompleted:e=>vi(e,x),calculatePlanningCompletion:()=>yi(x),onUpdateProject:Ws})})}),[jt.OKRS]:()=>(0,jn.jsx)(fc,{module:jt.OKRS,children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(or,{}),children:(0,jn.jsx)(Je,{module:"OKRs",projectId:x.id,children:(0,jn.jsx)(fd,{state:x,onUpdate:pi,onOpenTask:e=>{R(e),Y(jt.TASKS)},onNavigateToTasks:()=>Y(jt.TASKS),smartAction:It,onSmartActionHandled:()=>Ct(null)})})})}),[jt.TASKS]:()=>ge[jt.TASKS]?(0,jn.jsx)(er,{}):(0,jn.jsx)(fc,{module:jt.TASKS,children:(0,jn.jsx)(Je,{module:"Tasks",projectId:x.id,children:(0,jn.jsx)(pd,{state:x,onUpdate:pi,openTaskId:O,onTaskOpened:()=>R(null),updateEditingItem:Js,getUsersEditingItem:Qs,presenceUsers:Ys})})}),[jt.COMMUNICATION]:()=>(0,jn.jsx)(fc,{module:jt.COMMUNICATION,children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(ur,{}),children:(0,jn.jsx)(Je,{module:"Communication",projectId:x.id,children:(0,jn.jsx)(ru,{projectId:x.id,projectName:x.name,onLastMessageChange:xt,recentMessagesRef:_t,initialChannel:L,initialMessageId:$,onPopOutVoice:Wt,globalVoiceActive:Et,onStopGlobalVoice:Ht})})})}),[jt.WHITEBOARD]:()=>(0,jn.jsx)(fc,{module:jt.WHITEBOARD,children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(kr,{}),children:(0,jn.jsx)(Je,{module:"Whiteboard",projectId:x.id,children:(0,jn.jsx)(Pd,{projectId:x.id,toolsOnlyMode:x.toolsOnlyMode,onSelectedElementsChange:Wr,importIntent:q?.module===jt.WHITEBOARD?q.intent:null,onImportHandled:V})})})}),[jt.CALENDAR]:()=>(0,jn.jsx)(fc,{module:jt.CALENDAR,children:(0,jn.jsx)(Je,{module:"Calendar",projectId:x.id,children:(0,jn.jsx)(Ud,{projectId:x.id,importIntent:q?.module===jt.CALENDAR?q.intent:null,onImportHandled:V})})}),[jt.DRIVE]:()=>(0,jn.jsx)(fc,{module:jt.DRIVE,children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)(Ir,{}),children:(0,jn.jsx)(Je,{module:"Drive",projectId:x.id,children:(0,jn.jsx)(Fd,{state:x})})})}),[jt.GROWTH]:()=>(0,jn.jsx)(fc,{module:jt.GROWTH,children:(0,jn.jsx)(Je,{module:"Growth",projectId:x.id,children:(0,jn.jsx)(Yd,{state:x,onUpdate:pi})})}),[jt.FINANCE_DASHBOARD]:()=>(0,jn.jsx)(fc,{module:jt.FINANCE_DASHBOARD,children:(0,jn.jsx)(Je,{module:"Finance Dashboard",projectId:x.id,children:(0,jn.jsx)(yd,{state:x,onUpdate:pi})})}),[jt.INVESTOR_PIPELINE]:()=>(0,jn.jsx)(fc,{module:jt.INVESTOR_PIPELINE,children:(0,jn.jsx)(Je,{module:"Fundraising",projectId:x.id,children:(0,jn.jsx)(wd,{state:x,onUpdate:pi})})}),[jt.CRM]:()=>(0,jn.jsx)(fc,{module:jt.CRM,children:(0,jn.jsx)(Je,{module:"CRM",projectId:x.id,children:(0,jn.jsx)(Nd,{state:x,importIntent:q?.module===jt.CRM?q.intent:null,onImportHandled:V})})}),[jt.MAIL]:()=>Kr||Hr?(0,jn.jsx)(fc,{module:jt.MAIL,children:(0,jn.jsx)(Je,{module:"Mail",projectId:x.id,children:Hr?(0,jn.jsx)(Sd,{}):(0,jn.jsx)(kd,{state:x})})}):null,[jt.RISK]:()=>(0,jn.jsx)(fc,{module:jt.RISK,children:(0,jn.jsx)(Je,{module:"Risk Analysis",projectId:x.id,children:(0,jn.jsx)(Od,{state:x,onUpdate:pi,onNext:()=>{}})})}),[jt.PRICING]:()=>(0,jn.jsx)(fc,{module:jt.PRICING,children:(0,jn.jsx)(Je,{module:"Pricing",projectId:x.id,children:(0,jn.jsx)(Rd,{state:x,onUpdate:pi,onNext:()=>{}})})}),[jt.COMPETITOR_WAR_ROOM]:()=>(0,jn.jsx)(fc,{module:jt.COMPETITOR_WAR_ROOM,children:(0,jn.jsx)(Je,{module:"Competitors",projectId:x.id,children:(0,jn.jsx)(Qd,{state:x,onUpdate:pi})})}),[jt.MENTOR]:()=>(0,jn.jsx)(fc,{module:jt.MENTOR,children:(0,jn.jsx)(Je,{module:"Assad",projectId:x.id,children:(0,jn.jsx)(Ad,{state:x,onUpdate:pi,activeModule:B,onPopOutVoice:Wt})})}),[jt.HR]:()=>(0,jn.jsx)(fc,{module:jt.HR,children:(0,jn.jsx)(Je,{module:"HR",projectId:x.id,children:(0,jn.jsx)(Dd,{state:x})})}),[jt.GITHUB]:()=>(0,jn.jsx)(fc,{module:jt.GITHUB,children:(0,jn.jsx)(Je,{module:"GitHub",projectId:x.id,children:(0,jn.jsx)($d,{state:x})})}),[jt.GAME]:()=>(0,jn.jsx)(fc,{module:jt.GAME,children:(0,jn.jsx)("div",{className:"h-[calc(100dvh-120px)] bg-[#1a1a1a] rounded-xl overflow-hidden",children:(0,jn.jsx)(Wd,{state:x,onUpdate:pi,activeModule:B,coaches:wu,paSettings:yu})})})}),persistentRenderers:[{module:jt.MEETINGS,visible:B===jt.MEETINGS,enabled:!1!==Vr[jt.MEETINGS]?.active&&Zr(jt.MEETINGS),render:()=>(0,jn.jsx)(fc,{module:jt.MEETINGS,children:(0,jn.jsx)(Je,{module:"Meetings",projectId:x.id,children:(0,jn.jsx)(Ld,{projectId:x.id,autoOpenMeetingId:W,onAutoOpened:H})})})}]},x.id)})]})]})]}),(0,jn.jsx)(nu,{currentProject:x,onNavigateToModule:e=>Y(e),onOpenTask:e=>Vn({taskId:e}),onOpenNote:e=>Vn({noteId:e}),onOpenChannel:e=>Vn({channel:e}),onOpenOkr:e=>Vn({okrId:e}),onQuickCreateTask:ta?void 0:async e=>{const t=e.trim();t&&await Hs({title:t,sourceModule:B})&&Ae.success(dt("app.task_created_named",{title:t}))},onQuickCreateNote:ta?void 0:async t=>{const r=t.trim(),a=js.current?.id;if(!r||!a||!e)return;const{data:s,error:n}=await Lt.from("project_documents").insert({project_id:a,user_id:e.id,title:r,blocks:[{id:D(),type:"paragraph",content:""}],is_folder:!1,is_pinned:!1,is_archived:!1}).select("id").maybeSingle();if(n||!s)return Ge.error("Failed to create a note from the command palette",n,{projectId:a}),void Ae.error(dt("app.note_create_failed"));Ae.success(dt("app.note_created_named",{title:r})),js.current?.id===a&&Vn({noteId:s.id})},onQuickCreateGoal:ta?void 0:async e=>
2{const t=e.trim(),r=js.current?.id;if(!t||!r)return;const a={id:D(),title:t,quarter:`Q${Math.ceil(((new Date).getMonth()+1)/3)} ${(new Date).getFullYear()}`,category:"company",keyResults:[],isArchived:!1};try{await ss(r,e=>({...e,objectives:[...e.objectives,a]})),Ae.success(dt("app.goal_created_named",{title:t}),{action:{label:dt("action.open"),onClick:()=>{js.current?.id===r&&Vn({okrId:a.id})}}})}catch(s){Ge.error("Failed to create goal from the command palette",s,{projectId:r}),Ae.error(dt("app.goal_create_failed"))}},onQuickSendChat:async(t,r)=>{const a=r.trim();if(!a||!x||!e)return;const{error:s}=await Lt.from("team_chat_messages").insert({project_id:x.id,user_id:e.id,channel:t,content:a,message_type:"text"});s?(Ge.error("Failed to send a message from the command palette",s,{projectId:x.id}),Ae.error(dt("app.message_send_failed"))):Ae.success(dt("app.sent_to_channel",{channel:t}))}}),(0,jn.jsx)(ou,{hidden:B!==jt.DASHBOARD||ta,activeModule:B,onQuickTask:()=>pt(!0),onQuickNote:async()=>{if(!e)return;const t=x.id,{data:r,error:a}=await Lt.from("project_documents").insert({project_id:t,user_id:e.id,title:"Untitled Note",is_folder:!1}).select("id").maybeSingle();if(a||!r)return Ge.error("Failed to create a quick note",a,{projectId:t}),void Ae.error(dt("app.note_create_failed"));Ae.success(dt("app.note_created")),js.current?.id===t&&Vn({noteId:r.id})},onQuickChat:()=>Y(jt.COMMUNICATION),onQuickWhiteboard:()=>Y(jt.WHITEBOARD)}),x&&!ta&&(0,jn.jsx)(lu,{open:mt,onOpenChange:pt,sourceModule:B,sourceContext:B===jt.COMMUNICATION?gt:B===jt.WHITEBOARD?Fr.filter(e=>e.text).map(e=>e.text).join("\n")||"":(()=>{try{return window.getSelection()?.toString()||""}catch{return""}})(),onCreateTask:async e=>{const t=await Hs({id:e.id,title:e.title,description:e.description,priority:e.priority,sourceModule:B,sourceTitle:e.tags?.[0]?.replace("from-","").replace(/-/g," ")||B});return t&&Ae.success(dt("app.task_created")),t}}),(0,jn.jsx)(mu,{open:vt.open,onOpenChange:e=>yt(t=>({...t,open:e})),type:vt.type,id:vt.id,tasks:x.tasks||[],okrs:x.okrs?.objectives||[],projectId:x.id,onNavigate:e=>{"task"===e?Y(jt.TASKS):"okr"===e?Y(jt.OKRS):"note"===e&&Y(jt.NOTES)}}),at&&(0,jn.jsx)(tu,{open:it,onOpenChange:e=>{lt(e),e||nt(null)},projectId:at,onImportComplete:e=>{e?.whiteboardId&&x.id===at&&Y(jt.WHITEBOARD)}}),(0,jn.jsx)(Pc,{currentProject:x,activeModule:B,setActiveModule:Y,showExecutionWelcome:Fe,setShowExecutionWelcome:We,calculatePlanningCompletion:yi,planningNavItems:_i,isModuleCompleted:vi,pendingTransition:ca,showTransitionCoach:oa,setShowTransitionCoach:la,setPendingTransition:da,handleTransitionContinue:Tn,handleTransitionGoBack:An,handleDisableTransitionCoach:En,lastCoachAnalysis:ua,lastAnalyzedModule:ha,setLastCoachAnalysis:pa,setLastAnalyzedModule:ba,showOnboardingWizard:tt,setShowOnboardingWizard:rt,handleOnboardingComplete:ui,showPortfolioOnboarding:Ke,setShowPortfolioOnboarding:Qe,showCrossModuleTemplateDialog:ct,setShowCrossModuleTemplateDialog:ut,directUpdateProject:Ws,globalVoiceActive:Et,globalVoiceProjectId:At,globalVoiceThreadId:Mt,globalVoiceSettings:Ot,handlePopOutVoice:Wt,handleStopGlobalVoice:Ht}),(0,jn.jsx)(fn.Suspense,{fallback:null,children:(0,jn.jsx)(fu,{projectId:x?.id??null})})]})})})}):y?(0,jn.jsxs)("div",{className:"min-h-screen bg-background flex flex-col items-center justify-center gap-4 text-muted-foreground",children:[(0,jn.jsx)("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"}),(0,jn.jsx)("p",{className:"text-sm font-medium",children:N??(Zt?.projectName?`Opening ${Zt.projectName}â¦`:"Opening projectâ¦")})]}):(0,jn.jsx)(Tr,{reducedMotion:"user",children:(0,jn.jsx)(fn.Suspense,{fallback:(0,jn.jsx)("div",{className:"min-h-screen bg-background"}),children:(0,jn.jsx)(ot,{language:st(),children:(0,jn.jsxs)("div",{className:"app-accessible-theme min-h-screen bg-background text-foreground transition-colors duration-300 selection:bg-primary/30 overflow-x-hidden",children:[(0,jn.jsx)("a",{href:"#main-content",className:"sr-only focus:not-sr-only focus:fixed focus:left-4 focus:top-4 focus:z-[1200] focus:rounded-md focus:bg-background focus:px-4 focus:py-3 focus:text-foreground focus:shadow-lg focus:outline-none focus:ring-2 focus:ring-ring",children:"Skip to main content"}),(0,jn.jsxs)("header",{className:"max-w-7xl mx-auto px-3 sm:px-6 h-16 sm:h-24 flex items-center justify-between gap-2",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 sm:gap-3 min-w-0 shrink-0",children:[(0,jn.jsx)("img",{src:et,alt:"1tab.ai",className:"w-9 h-9 sm:w-10 sm:h-10 rounded-xl object-contain shrink-0"}),(0,jn.jsxs)("div",{className:"min-w-0",children:[(0,jn.jsx)("span",{className:"font-bold text-lg sm:text-xl tracking-tight block leading-none",children:"1tab.ai"}),(0,jn.jsx)("span",{className:"text-[10px] uppercase font-bold tracking-widest text-muted-foreground hidden sm:block",children:"We help you create your startup"})]})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-1 sm:gap-2 shrink-0",children:[(0,jn.jsx)(rd,{online:yn,syncStatus:wn,pendingCount:Nn,conflictCount:kn,lastSyncTime:Sn,onSync:In,compact:!0}),(0,jn.jsx)(Gc,{}),(0,jn.jsx)(Bc,{children:(0,jn.jsx)(zc,{})}),(0,jn.jsx)(rn,{variant:"app"}),(0,jn.jsx)(Ye,{variant:"ghost",size:"icon",className:"h-9 w-9",title:"Search (Cmd+K)","aria-label":"Search",onClick:()=>window.dispatchEvent(new Event("open-command-palette")),children:(0,jn.jsx)(k,{className:"w-5 h-5"})}),(0,jn.jsx)(kc,{theme:ve,onToggleTheme:Fn,onLogout:Hn,projectIds:g,showExtras:!0,onOpenWallet:()=>{document.querySelector("[data-portfolio-wallet-trigger]")?.click()},onOpenNews:()=>{document.querySelector("[data-portfolio-news-trigger]")?.click()}}),(0,jn.jsxs)("div",{className:"hidden",children:[(0,jn.jsx)(Bc,{children:(0,jn.jsx)("button",{"data-portfolio-wallet-trigger":!0})}),(0,jn.jsx)(Vd,{trigger:(0,jn.jsx)("button",{"data-portfolio-news-trigger":!0})})]})]})]}),(0,jn.jsx)("div",{className:"max-w-7xl mx-auto px-3 sm:px-6 mt-2 sm:mt-4",children:(0,jn.jsx)(zd,{})}
2),(0,jn.jsxs)("main",{id:"main-content",tabIndex:-1,className:"max-w-7xl mx-auto px-3 sm:px-6 py-4 sm:py-12 pb-8 lg:pb-12",children:[y&&(0,jn.jsxs)("div",{className:"fixed inset-0 z-50 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center gap-3",children:[(0,jn.jsx)(ce,{className:"w-8 h-8 animate-spin text-primary"}),(0,jn.jsx)("p",{className:"text-sm text-muted-foreground",children:"Opening project..."})]}),0===h.length&&(0,jn.jsxs)("div",{className:"text-center max-w-4xl mx-auto space-y-5 animate-in slide-in-from-bottom-8 duration-700 pt-2 pb-8",children:[(0,jn.jsx)("div",{className:"flex justify-center",children:(0,jn.jsx)("div",{"data-tutorial":"empty-hero",className:"w-20 h-20 rounded-full bg-gradient-to-br from-[hsl(var(--hero-gradient-start))]/20 via-[hsl(var(--hero-gradient-mid))]/20 to-[hsl(var(--hero-gradient-end))]/20 flex items-center justify-center border border-primary/20 shadow-lg shadow-primary/10",children:(0,jn.jsx)("img",{src:"/assets/1tab-logo-CzkPWWPJ.png",alt:"1tab.ai",className:"w-10 h-10 rounded-2xl object-contain"})})}),(0,jn.jsxs)("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full bg-muted border border-border text-muted-foreground text-xs font-bold uppercase tracking-wider",children:[(0,jn.jsx)(se,{className:"w-3.5 h-3.5 text-primary"}),(0,jn.jsx)("span",{children:"Your AI Co-founder for Startups"})]}),(0,jn.jsxs)("h1",{className:"text-4xl md:text-6xl font-extrabold tracking-tight leading-[1.1]",children:["Build the ",(0,jn.jsx)("span",{className:"text-gradient",children:"Future."}),(0,jn.jsx)("br",{}),(0,jn.jsx)("span",{className:"text-muted-foreground",children:"Faster."})]}),(0,jn.jsx)("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto leading-relaxed",children:"From napkin sketch to IPO. Validate ideas, generate business strategies, design branding, and plan executionâall in one intelligent workspace."}),(0,jn.jsxs)("button",{onClick:di,"data-tutorial":"new-project",className:"group inline-flex items-center px-8 py-4 bg-gradient-to-r from-[hsl(var(--hero-gradient-start))] via-[hsl(var(--hero-gradient-mid))] to-[hsl(var(--hero-gradient-end))] text-primary-foreground font-bold text-lg rounded-full shadow-xl hover:shadow-2xl hover:shadow-primary/30 transition-all duration-300 hover:-translate-y-0.5",children:[(0,jn.jsx)(Ee,{className:"w-5 h-5 mr-2 group-hover:rotate-90 transition-transform"}),"Start Your First Venture"]}),(0,jn.jsxs)("div",{className:"flex flex-wrap items-center justify-center gap-4 mt-4",children:[(0,jn.jsxs)(Ye,{variant:"outline",size:"sm",onClick:()=>o("/demo"),"data-tutorial":"explore-demo",className:"rounded-full gap-2",children:[(0,jn.jsx)(Ie,{className:"w-4 h-4"})," Explore a Demo"]}),(0,jn.jsxs)(Ye,{variant:"ghost",size:"sm",onClick:()=>ei(),className:"rounded-full gap-2",children:[(0,jn.jsx)(se,{className:"w-4 h-4"})," Take a Quick Tour"]})]})]}),(0,jn.jsx)("div",{className:"mb-4",children:(0,jn.jsx)(Hd,{onInviteAccepted:()=>ds(e.id).then(f)})}),Zt&&!cr&&!x&&h.length>0&&(()=>{const e=h.find(e=>e.id===Zt.projectId);if(!e)return null;const t=qt(Zt.module);return(0,jn.jsx)(Ar,{children:!cr&&(0,jn.jsx)(Er.div,{initial:{opacity:1,height:"auto"},exit:{opacity:0,height:0,marginBottom:0},transition:{duration:.3,ease:"easeOut"},className:"mb-6",children:(0,jn.jsxs)("div",{className:"flex items-center gap-3 px-4 py-3 rounded-xl bg-primary/5 border border-primary/20 hover:bg-primary/10 transition-colors group",children:[(0,jn.jsx)("div",{className:"w-10 h-10 rounded-lg bg-primary/15 flex items-center justify-center text-primary font-bold text-lg shrink-0",children:(e.name||"P").charAt(0).toUpperCase()}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,jn.jsx)("p",{className:"text-xs text-muted-foreground font-medium",children:"Continue where you left off"}),(0,jn.jsxs)("p",{className:"text-sm font-semibold truncate",children:[e.name," ",(0,jn.jsxs)("span",{className:"text-muted-foreground font-normal",children:["â ",t]})]})]}),(0,jn.jsx)("button",{onClick:()=>{Bn(Zt.projectId),yr(!0)},className:"shrink-0 px-3 py-1.5 text-xs font-bold bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"Open"}),(0,jn.jsx)("button",{onClick:()=>yr(!0),className:"shrink-0 p-1 text-muted-foreground hover:text-foreground transition-colors rounded",title:"Dismiss",children:(0,jn.jsx)(J,{className:"w-4 h-4"})})]})})})})(),h.length>0&&(0,jn.jsxs)("div",{className:"animate-in fade-in duration-1000 delay-200 mb-6",children:[(0,jn.jsxs)("div",{className:"flex flex-wrap items-center gap-2 sm:gap-4 mb-6 px-2",children:[(0,jn.jsxs)("div",{className:"relative flex-1 sm:flex-none",children:[(0,jn.jsx)(k,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),(0,jn.jsx)("input",{type:"text",placeholder:"Search projects...",value:Re,onChange:e=>Me(e.target.value),className:"pl-9 pr-3 py-2 text-sm bg-card border border-border rounded-lg text-foreground w-full sm:w-40 md:w-56 focus:outline-none focus:ring-2 focus:ring-primary/30"})]}),(0,jn.jsxs)("select",{value:Te,onChange:e=>De(e.target.value),className:"hidden sm:block px-3 py-2 text-sm bg-card border border-border rounded-lg text-foreground min-w-0",children:[(0,jn.jsx)("option",{value:"all",children:"All Projects"}),(0,jn.jsx)("option",{value:"owned",children:"My Projects"}),(0,jn.jsx)("option",{value:"shared",children:"Shared with Me"})]}),(0,jn.jsxs)("select",{value:Pe,onChange:e=>Le(e.target.value),className:"hidden sm:block px-3 py-2 text-sm bg-card border border-border rounded-lg text-foreground min-w-0",children:[(0,jn.jsx)("option",{value:"lastEdited",children:"Last Edited"}),(0,jn.jsx)("option",{value:"newest",children:"Newest First"}),(0,jn.jsx)("option",{value:"alphabetical",children:"Alphabetical"}),(0,jn.jsx)("option",{value:"favorites",children:"Favorites First"})]}),(0,jn.jsxs)(lr,{children:[(0,jn.jsx)(_r,{asChild:!0,children:(0,jn.jsxs)("button",{className:"sm:hidden flex items-center gap-1.5 px-3 py-2 text-sm bg-card border border-border rounded-lg text-foreground",children:[(0,jn.jsx)(xe,{className:"w-3.5 h-3.5"})," Filter"]})}),(0,jn.jsxs)(rr,{side:"bottom",className:"rounded-t-2xl",children:[(0,jn.jsx)(tr,{children:(0,jn.jsx)(sr,{children:"Filter & Sort"})}),(0,jn.jsxs)("div",{className:"space-y-4 pt-4",children:[(0,jn.jsxs)("div",{children:[(0,jn.jsx)("label",{className:"text-xs font-medium text-muted-foreground mb-1.5 block",children:"Show"}),(0,jn.jsxs)("select",{value:Te,onChange:e=>De(e.target.value),className:"w-full px-3 py-2.5 text-sm bg-card border border-border rounded-lg text-foreground",children:[(0,jn.jsx)("option",{value:"all",children:"All Projects"}),(0,jn.jsx)("option",{value:"owned",children:"My Projects"}),(0,jn.jsx)("option",{value:"shared",children:"Shared with Me"})]})]}),(0,jn.jsxs)("div",{children:[(0,jn.jsx)("label",{className:"text-xs font-medium text-muted-foreground mb-1.5 block",children:"Sort by"}),(0,jn.jsxs)("select",{value:Pe,onChange:e=>Le(e.target.value),className:"w-full px-3 py-2.5 text-sm bg-card border border-border rounded-lg text-foreground",children:[(0,jn.jsx)("option",{value:"lastEdited",children:"Last Edited"}),(0,jn.jsx)("option",{value:"newest",children:"Newest First"}),(0,jn.jsx)("option",{value:"alphabetical",children:"Alphabetical"}),(0,jn.jsx)("option",{value:"favorites",children:"Favorites First"})]})]})]})]})]}),(0,jn.jsxs)("button",{type:"button",onClick:di,"aria-label":"New Project",className:"flex items-center gap-2 text-sm font-bold text-primary hover:bg-primary/10 px-3 sm:px-4 py-2 rounded-lg transition-colors ml-auto",children:[(0,jn.jsx)(Ee,{className:"w-4 h-4","aria-hidden":"true"})," ",(0,jn.jsx)("span",{className:"hidden sm:inline",children:"New Project"})]})]}),(0,jn.jsx)("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-6","data-tutorial":"projects-grid",children:j?(0,jn.jsx)(jn.Fragment,{children:[1,2,3].map(e=>(0,jn.jsxs)("div",{className:"flex flex-col p-4 sm:p-6 border border-border rounded-2xl min-h-[160px] sm:min-h-[280px] space-y-3 sm:space-y-4",children:[(0,jn.jsx)(ma,{className:"w-16 h-16 sm:w-32 sm:h-32 rounded-xl"}),(0,jn.jsx)(ma,{className:"h-6 w-3/4"}),(0,jn.jsx)(ma,{className:"h-4 w-full"}),(0,jn.jsx)(ma,{className:"h-4 w-2/3"}),(0,jn.jsx)("div",{className:"mt-auto pt-3 sm:pt-4 border-t border-border",children:(0,jn.jsx)(ma,{className:"h-3 w-full"})})]},e))}):(0,jn.jsxs)(jn.Fragment,{children:[0===Mn.length&&(0,jn.jsxs)("button",{onClick:di,"data-tutorial":"new-project",className:"group flex flex-col items-center justify-center p-4 sm:p-8 border-2 border-dashed border-border rounded-2xl hover:border-primary hover:bg-card transition-all min-h-[80px] sm:min-h-[280px]",children:[(0,jn.jsx)("div",{className:"w-10 h-10 sm:w-20 sm:h-20 rounded-full bg-muted group-hover:bg-primary/15 flex items-center justify-center sm:mb-6 transition-colors duration-300",children:(0,jn.jsx)(Ee,{className:"w-5 h-5 sm:w-10 sm:h-10 text-muted-foreground group-hover:text-primary"})}),(0,jn.jsx)("span",{className:"font-bold text-sm sm:text-lg text-muted-foreground group-hover:text-primary transition-colors ml-3 sm:ml-0",children:"New Project"}),(0,jn.jsx)("p",{className:"text-sm text-muted-foreground mt-2 max-w-[200px] hidden sm:block",children:"Start building your startup"}
2),(0,jn.jsxs)("p",{className:"text-xs text-muted-foreground/60 mt-3 hidden sm:block",children:["Pro tip: Press ",(0,jn.jsx)("kbd",{className:"px-1.5 py-0.5 bg-muted border border-border rounded text-[10px] font-mono",children:"N"})," on this page"]})]}),Mn.map(t=>{const r=!1!==t.isOwner,a=!0===t.isTemplate,s=!!t.refinedPitch;if(a){const e=t.name.toLowerCase().includes("studystack");return(0,jn.jsxs)("div",{role:"button",tabIndex:0,"aria-label":`Open ${t.name}`,onClick:()=>Bn(t.id),onKeyDown:e=>{"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),Bn(t.id))},"data-tutorial":e?"template-studystack":void 0,className:"group relative bg-warning-soft border-2 border-warning/30 hover:border-warning/60 rounded-2xl p-4 sm:p-6 cursor-pointer transition-all hover:-translate-y-1 hover:shadow-2xl hover:shadow-warning/10 flex flex-col min-h-[160px] sm:min-h-[280px]",children:[(0,jn.jsxs)("div",{className:"absolute top-3 right-3 flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-warning text-warning-foreground text-[10px] font-bold shadow-lg",children:[(0,jn.jsx)(ae,{className:"w-3 h-3"}),"EXAMPLE"]}),(0,jn.jsx)("div",{className:"flex items-start justify-between mb-2 sm:mb-4",children:(0,jn.jsx)("div",{className:"relative",children:(0,jn.jsx)("div",{className:"w-16 h-16 sm:w-32 sm:h-32 rounded-xl bg-warning-soft flex items-center justify-center text-3xl sm:text-5xl font-bold border border-warning/30 shadow-inner overflow-hidden",children:t.logoUrl?(0,jn.jsx)("img",{src:t.logoUrl,alt:t.name,className:"w-full h-full object-cover"}):(0,jn.jsx)("span",{className:"text-warning-strong",children:(t.name||"P").charAt(0).toUpperCase()})})})}),(0,jn.jsxs)("div",{className:"flex-1 mt-2 sm:mt-4",children:[(0,jn.jsx)("h3",{className:"text-base sm:text-xl font-bold mb-1 sm:mb-2 text-warning-strong group-hover:text-warning transition-colors break-words whitespace-normal leading-snug",title:t.name,children:t.name}),(0,jn.jsx)("p",{className:"text-muted-foreground text-xs sm:text-sm line-clamp-2 sm:line-clamp-3 leading-relaxed",children:t.refinedPitch||"Explore this complete example project"})]}),(0,jn.jsx)("div",{className:"mt-2 sm:mt-4 pt-2 sm:pt-4 border-t border-warning/20",children:(0,jn.jsxs)("div",{className:"flex items-center justify-between",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-2 text-xs text-warning-strong",children:[(0,jn.jsx)(be,{className:"w-3 h-3"}),(0,jn.jsx)("span",{children:"Example / Template for you to adapt"})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[(0,jn.jsx)(ye,{className:"w-3 h-3"}),(0,jn.jsx)("span",{children:"Click to explore"})]})]})})]},t.id)}return(0,jn.jsxs)("div",{onClick:()=>Bn(t.id),className:"group relative bg-card border border-border hover:border-primary/50 rounded-2xl p-4 sm:p-6 cursor-pointer transition-all hover:-translate-y-1 hover:shadow-2xl hover:shadow-primary/10 flex flex-col min-h-[150px] sm:min-h-[280px]",children:[(0,jn.jsxs)("div",{className:"flex gap-3 sm:hidden flex-1",children:[(0,jn.jsx)("div",{className:"w-1/3 shrink-0 aspect-square self-start rounded-xl bg-gradient-to-br from-muted to-muted/50 flex items-center justify-center text-3xl font-bold border border-border shadow-inner overflow-hidden",children:t.logoUrl?(0,jn.jsx)("img",{src:t.logoUrl,alt:t.name,className:"w-full h-full object-cover"}):(0,jn.jsx)("span",{children:(t.name||"P").charAt(0).toUpperCase()})}),(0,jn.jsxs)("div",{className:"flex-1 min-w-0 flex flex-col",children:[(0,jn.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[(0,jn.jsx)("h3",{className:"text-base font-bold group-hover:text-primary transition-colors break-words leading-snug min-w-0",title:t.name,children:(0,jn.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),Bn(t.id)},"aria-label":`Open ${t.name}`,className:"text-left break-words rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:t.name})}),(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 shrink-0",children:[(0,jn.jsx)("button",{onClick:e=>$n(t.id,e),className:"p-1.5 rounded-full transition-colors "+(t.isFavorite?"text-warning":"text-muted-foreground"),title:t.is
2Favorite?"Remove from favorites":"Add to favorites",children:(0,jn.jsx)(je,{className:"w-4 h-4 "+(t.isFavorite?"fill-current":"")})}),r?(0,jn.jsx)("div",{onClick:e=>e.stopPropagation(),children:(0,jn.jsxs)(_a,{children:[(0,jn.jsx)(fa,{asChild:!0,children:(0,jn.jsx)("button",{className:"p-2 bg-card hover:bg-muted border border-border rounded-lg text-muted-foreground hover:text-foreground transition-colors shadow-sm","aria-label":"Project options",children:(0,jn.jsx)(p,{className:"w-4 h-4"})})}),(0,jn.jsxs)(ga,{align:"end",className:"w-40",children:[(0,jn.jsx)(xa,{asChild:!0,children:(0,jn.jsx)("div",{children:(0,jn.jsx)(Kd,{projectId:t.id,projectName:t.name,ownerId:t.userId||e?.id||"",trigger:(0,jn.jsxs)("button",{className:"flex items-center gap-2 w-full text-sm",children:[(0,jn.jsx)(G,{className:"w-3.5 h-3.5"})," Team"]})})})}),(0,jn.jsxs)(xa,{onClick:e=>fi(t.id,e),className:"text-destructive focus:text-destructive",children:[(0,jn.jsx)(J,{className:"w-3.5 h-3.5 mr-2"})," Delete"]})]})]})}):(0,jn.jsx)("div",{onClick:e=>e.stopPropagation(),children:(0,jn.jsx)(Kd,{projectId:t.id,projectName:t.name,ownerId:t.userId||"",trigger:(0,jn.jsx)("button",{className:"p-2 bg-card hover:bg-primary/10 border border-border rounded-lg text-muted-foreground hover:text-primary transition-colors shadow-sm",title:"View Team",children:(0,jn.jsx)(G,{className:"w-4 h-4"})})})})]})]}),(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap mt-1",children:[t.isShared&&(0,jn.jsx)("span",{className:"text-muted-foreground",title:"Shared project",children:(0,jn.jsx)(G,{className:"w-3 h-3"})}),(0,jn.jsxs)("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full border "+(t.toolsOnlyMode?"bg-success-soft text-success-strong border-success/30":"bg-primary/10 text-primary border-primary/30"),children:[t.toolsOnlyMode?"TOOLS":"FULL"," · ",s?"IN PROGRESS":"NEW"]})]}),(0,jn.jsx)("p",{className:"text-muted-foreground text-xs line-clamp-2 leading-relaxed mt-1.5",children:t.refinedPitch||"No description yet. Click to start defining your idea."}),(0,jn.jsxs)("div",{className:"mt-auto pt-2 border-t border-border space-y-1.5",children:[(0,jn.jsxs)("div",{className:"flex justify-between text-[11px] text-muted-foreground",children:[(0,jn.jsxs)("span",{children:["Created ",Pn.get(t.id)?.created??"N/A"]}),(0,jn.jsxs)("span",{children:["Edited ",Pn.get(t.id)?.edited??""]})]}),!t.toolsOnlyMode&&(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)("div",{className:"flex-1 h-1.5 bg-muted rounded-full overflow-hidden",children:(0,jn.jsx)("div",{className:"h-full bg-primary rounded-full transition-all duration-500",style:{width:(s?15:5)+"%"}})}),(0,jn.jsx)("span",{className:"text-[10px] text-muted-foreground font-medium",children:s?"In Progress":"New"})]})]})]})]}),(0,jn.jsxs)("div",{className:"hidden sm:flex sm:flex-col sm:flex-1",children:[(0,jn.jsxs)("div",{className:"flex items-start justify-between mb-2 sm:mb-4",children:[(0,jn.jsx)("div",{className:"w-16 h-16 sm:w-32 sm:h-32 rounded-xl bg-gradient-to-br from-muted to-muted/50 flex items-center justify-center text-3xl sm:text-5xl font-bold border border-border shadow-inner overflow-hidden",children:t.logoUrl?(0,jn.jsx)("img",{src:t.logoUrl,alt:t.name,className:"w-full h-full object-cover"}):(0,jn.jsx)("span",{children:(t.name||"P").charAt(0).toUpperCase()})}),(0,jn.jsxs)("div",{className:"flex flex-col items-end gap-1.5",children:[(0,jn.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,jn.jsx)("button",{onClick:e=>$n(t.id,e),className:"p-1.5 rounded-full transition-colors "+(t.isFavorite?"text-warning hover:text-warning-strong":"text-muted-foreground hover:text-warning opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100"),title:t.isFavorite?"Remove from favorites":"Add to favorites","aria-label":t.isFavorite?`Remove ${t.name} from favorites`:`Add ${t.name} to favorites`,children:(0,jn.jsx)(je,{className:"w-4 h-4 "+(t.isFavorite?"fill-current":"")})}),r&&(0,jn.jsx)("div",{className:"opacity-0 group-hover:opacity-100 lg:opacity-0 lg:group-hover:opacity-100 max-lg:opacity-100 group-focus-within:opacity-100 focus-within:opacity-100 transition-opacity",onClick:e=>e.stopPropagation(),children:(0,jn.jsxs)(_a,{children:[(0,jn.jsx)(fa,{asChild:!0,children:(0,jn.jsx)("button",{className:"p-2.5 sm:p-1.5 bg-card hover:bg-muted border border-border rounded-lg text-muted-foreground hover:text-foreground transition-colors shadow-sm","aria-label":"Project options",children:(0,jn.jsx)(p,{className:"w-4 h-4 sm:w-3.5 sm:h-3.5"})})}),(0,jn.jsxs)(ga,{align:"end",className:"w-40",children:[(0,jn.jsx)(xa,{asChild:!0,children:(0,jn.jsx)("div",{children:(0,jn.jsx)(Kd,{projectId:t.id,projectName:t.name,ownerId:t.userId||e?.
2id||"",trigger:(0,jn.jsxs)("button",{className:"flex items-center gap-2 w-full text-sm",children:[(0,jn.jsx)(G,{className:"w-3.5 h-3.5"})," Team"]})})})}),(0,jn.jsxs)(xa,{onClick:e=>fi(t.id,e),className:"text-destructive focus:text-destructive",children:[(0,jn.jsx)(J,{className:"w-3.5 h-3.5 mr-2"})," Delete"]})]})]})})]}),!r&&(0,jn.jsx)("div",{onClick:e=>e.stopPropagation(),children:(0,jn.jsx)(Kd,{projectId:t.id,projectName:t.name,ownerId:t.userId||"",trigger:(0,jn.jsx)("button",{className:"p-1.5 bg-card hover:bg-primary/10 border border-border rounded text-muted-foreground hover:text-primary transition-colors shadow-sm",title:"View Team",children:(0,jn.jsx)(G,{className:"w-3 h-3"})})})}),(0,jn.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap justify-end",children:[t.isShared&&(0,jn.jsx)("span",{className:"text-muted-foreground",title:"Shared project",children:(0,jn.jsx)(G,{className:"w-3.5 h-3.5"})}),(0,jn.jsxs)("span",{className:"text-[10px] font-bold px-2 py-0.5 rounded-full border "+(t.toolsOnlyMode?"bg-success-soft text-success-strong border-success/30":"bg-primary/10 text-primary border-primary/30"),children:[t.toolsOnlyMode?"TOOLS":"FULL"," · ",s?"IN PROGRESS":"NEW"]})]})]})]}),(0,jn.jsxs)("div",{className:"flex-1 mt-2 sm:mt-4",children:[(0,jn.jsx)("h3",{className:"text-base sm:text-xl font-bold mb-1 sm:mb-2 group-hover:text-primary transition-colors break-words whitespace-normal leading-snug",title:t.name,children:(0,jn.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),Bn(t.id)},"aria-label":`Open ${t.name}`,className:"text-left break-words whitespace-normal rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",children:t.name})}),(0,jn.jsx)("p",{className:"text-muted-foreground text-xs sm:text-sm line-clamp-2 sm:line-clamp-3 leading-relaxed",children:t.refinedPitch||"No description yet. Click to start defining your idea."})]}),(0,jn.jsxs)("div",{className:"mt-2 sm:mt-4 pt-2 sm:pt-4 border-t border-border space-y-2",children:[(0,jn.jsxs)("div",{className:"flex justify-between text-xs text-muted-foreground",children:[(0,jn.jsxs)("span",{children:["Created ",Pn.get(t.id)?.created??"N/A"]}),(0,jn.jsxs)("span",{children:["Edited ",Pn.get(t.id)?.edited??""]})]}),!t.toolsOnlyMode&&(0,jn.jsxs)("div",{className:"flex items-center gap-2",children:[(0,jn.jsx)("div",{className:"flex-1 h-1.5 bg-muted rounded-full overflow-hidden",children:(0,jn.jsx)("div",{className:"h-full bg-primary rounded-full transition-all duration-500",style:{width:(s?15:5)+"%"}})}),(0,jn.jsx)("span",{className:"text-[10px] text-muted-foreground font-medium",children:s?"In Progress":"New"})]})]})]})]},t.id)})]})})]})]}),(0,jn.jsx)(qd,{isOpen:!!Ue,projectName:ya?.name||"",onConfirm:gi,onCancel:()=>$e(null)}),(0,jn.jsx)(eu,{open:tt,onClose:()=>rt(!1),onComplete:ui}),(0,jn.jsx)(nu,{currentProject:null,onNavigateToModule:t=>{const r=(()=>{let t=null;try{t=ne(e.id,new Set(h.map(e=>e.id)))?.projectId??null}catch{}const r=h.filter(e=>!e.isTemplate).sort((e,t)=>t.lastUpdated-e.lastUpdated);return h.find(e=>e.id===t)??r[0]??h[0]})();r?Bn(r.id,void 0,t):Ae.error(dt("app.create_project_first"))},onOpenTask:(e,t)=>{t&&Bn(t,e,jt.TASKS)},onOpenNote:(e,t)=>{t&&Bn(t,void 0,jt.NOTES,{note:e})},onOpenChannel:(e,t)=>{t&&Bn(t,void 0,jt.COMMUNICATION,{channel:e})}})]})})})})},ku=()=>{const{user:e}=$t(),t=Wt(e?.id);return(0,jn.jsx)(Nu,{},t)};export{yn as $,$i as A,ji as B,go as C,so as D,oo as E,Ci as F,hi as G,di as H,Ei as I,si as J,zn as K,ki as L,Fi as M,Qi as N,Zi as O,Mi as P,Cn as Q,yi as R,co as S,lo as T,ci as U,pi as V,gi as W,Vn as X,qn as Y,An as Z,jo as _,Vl as a,uo as b,Rl as c,bl as d,ku as default,vn as et,Yo as f,vo as g,wo as h,Zl as i,Wi as j,Pi as k,wl as l,ko as m,tc as n,Pl as o,Io as p,ni as q,rc as r,Ml as s,md as t,bn as tt,_l as u,ho as v,fo as w,mo as x,po as y,Ni as z};
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.