1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ProjectManagementHub-VoDKLZdn.js","assets/index-Epr9psQo.js","assets/vendor-radix-BnNg3BH5.js","assets/vendor-react-67mgcWXU.js","assets/vendor-supabase-CTlrDMdV.js","assets/vendor-charts-Dck3qfzI.js","assets/vendor-query-PMAhJHCS.js","assets/vendor-motion-CSzk-Fqg.js","assets/index-D4Cg7d-c.css","assets/badge-Cl7apleB.js","assets/progress-OXAVVpg3.js","assets/collapsible-CKRfPF8i.js","assets/index-Jdtl9AIN.js","assets/dropdown-menu-Duf4NJvQ.js","assets/chevron-right-DQtszqux.js","assets/circle-CPv7M1K7.js","assets/sidebar-BBoeMq0-.js","assets/use-mobile-B1ZU7MF_.js","assets/separator-C2IB9E9R.js","assets/sheet-BMVGKQ_l.js","assets/skeleton-CXDkv5zX.js","assets/panel-left-1hXsOURo.js","assets/formatLabel-C4RR0vUw.js","assets/format-Bw8okCdv.js","assets/en-US-DJiZ5LCQ.js","assets/addDays-Cy4sUjNt.js","assets/parseISO-BkGvA2JK.js","assets/differenceInDays-BZV22iX5.js","assets/scroll-area-OnGFamwr.js","assets/plus-DRTmwF2W.js","assets/chevron-left-D3yfuHpM.js","assets/triangle-alert-C6ISfBPd.js","assets/flag-BJdgpYpl.js","assets/eachDayOfInterval-DEtVpE5g.js","assets/endOfWeek-Bk3y437X.js","assets/isSameDay-YWnicZiN.js","assets/isWeekend-SjMdRr51.js","assets/popover-C2IiMjDe.js","assets/TaskCompletionDialog-VPMzd5Si.js","assets/rich-text-editor-DxpU86F6.js","assets/vendor-editor-CEJKB4cc.js","assets/sanitizeHtml-CdEpntpt.js","assets/toggle-rMFllBbq.js","assets/useSpeechRecognition-Cyc-mF6g.js","assets/list-Cd7HYcio.js","assets/quote-Bthj736x.js","assets/link-D3nquTTi.js","assets/mic-eFw98pWv.js","assets/circle-check-Cv8aCTuA.js","assets/pencil-PwBd4M7u.js","assets/checkbox-CaPhqoy3.js","assets/sparkles-BcySMUTB.js","assets/clock-BYWbH6MV.js","assets/trash-2-EIFrPvgK.js","assets/avatar-DkXZyfFy.js","assets/addWeeks-QA4EuLDh.js","assets/isSameMonth-DowG56g5.js","assets/isWithinInterval-iv8YYnTs.js","assets/user-BG8cpmCD.js","assets/calendar-Dg9oKd3C.js","assets/subDays-O0YAIy_S.js","assets/startOfMonth-DSkvSDwv.js","assets/endOfMonth-BJH_LSY0.js","assets/addMonths-CAHQ-5pQ.js","assets/differenceInCalendarMonths-CBq9QhqA.js","assets/isAfter-CsIPKNJY.js","assets/addYears-BaWD3Fpv.js","assets/dollar-sign-CC-jyV1q.js","assets/trending-up-CXZcoU_y.js","assets/trending-down-CFwiQb3W.js","assets/gauge-mfYImdAE.js","assets/calendar-Ce69BthR.js","assets/activity-DehK1-wv.js","assets/formatDistanceToNow--Gw1Xv78.js","assets/constructNow-LutmP3uJ.js","assets/differenceInMonths-ODK8TVL-.js","assets/endOfDay-CV7hhp0x.js","assets/differenceInMilliseconds-BS2m-4UB.js","assets/card-DpKBVi42.js","assets/switch-ZTMCvIb3.js","assets/useBillingRecommendations-OvSMMTob.js","assets/useTeamworkSync-CLV1A5y_.js","assets/upload-2-rh2XwF.js","assets/paperclip-BZ4mElSl.js","assets/download-CDzT20jl.js","assets/file-D62hmXlJ.js","assets/image-BEkCpDIa.js","assets/message-square-7cL_4-It.js","assets/TaskDetailDrawer-DCc3zUQ9.js","assets/ellipsis-C6BfvtHH.js","assets/circle-alert-CFN03ksH.js","assets/moduleEvents-B5yqdP_9.js","assets/rows-3-D_curWmH.js","assets/grip-vertical-eNKORDT2.js","assets/isToday-ez2Bh_ph.js","assets/subMonths-Cf3G1AKu.js","assets/metric-DK0Tcl4m.js","assets/refresh-cw-j1umLsSM.js","assets/list-todo-BS9RmsVo.js","assets/edgeFunctionError-Sz55aoNN.js","assets/pause-BywH4XAI.js","assets/git-branch-BLkPAM3N.js","assets/maximize-2-NDiFjZZT.js","assets/alert-BbCCz1lQ.js","assets/calendar-days-CC-j__Br.js","assets/circle-x-HEsvXgN2.js","assets/file-search-BlEiu-k-.js","assets/database-C-966MCo.js","assets/pen-BjcYRxrI.js","assets/save-B2-eOoIe.js","assets/brain-BAvvPRM1.js","assets/users-uAR6_Qvs.js","assets/arrow-right-LjC5fuTq.js","assets/user-x-Dq8IMr2H.js","assets/target-CyHaUH9t.js","assets/dialog-scroll-area-BrjDoazS.js","assets/useStreamingAI-P9mQEfIN.js","assets/index-BMcbOcU5.js","assets/copy-C-Qie2rJ.js","assets/slider-D3QIa8DR.js","assets/index.browser-BNPOoOB3.js","assets/calculator-4oGLHdIn.js","assets/arrow-left-BKCvbsa9.js","assets/info-DuvYtGx9.js","assets/table-023rHGnC.js","assets/kanban-B6qmqqtt.js","assets/table-C94PLi9h.js","assets/search-BnpyGpZl.js","assets/filter-idQrjp7H.js","assets/layers-ByEfk1Gr.js","assets/ProgramDashboard-Cy4-nDgy.js","assets/calendar-clock-Dgofoxff.js","assets/arrow-up-right-zF0c4Zfm.js","assets/DecisionLog-DR7W_BU8.js","assets/scale-Cc_B3FHe.js","assets/link-2-Bu8oQt2W.js","assets/ProjectDeliverablesTab-Bj-k_2Cd.js","assets/package-DW7ssg6N.js","assets/external-link-DnfaRxEP.js","assets/dnd.esm-BsK0xBzW.js","assets/DeliverableFormDialog-DgBBE8go.js","assets/building-2-DODpaxwc.js","assets/book-open-CDTjHrJx.js","assets/presentation-LZafSl8u.js","assets/file-output-YR-TsISn.js","assets/shuffle-CEkClAtw.js","assets/ProjectTeamAssignment-vy5Ilv3o.js","assets/user-minus-qCg8sxPr.js","assets/user-plus-Cz5haDJC.js","assets/user-check-tdG2KrIL.js","assets/settings-2-rw5RGAbH.js","assets/ProjectFileBrowser-Dy68yWZS.js","assets/index-OJZrzQMP.js","assets/exceljs.min-os-CnBin.js","assets/_commonjs-dynamic-modules-TDtrdbi3.js","assets/jszip.min-C-g80qGt.js","assets/extractPdfText-B4RpLJZd.js","assets/pdf-DxqAUlXS.js","assets/pdf.worker.min-D8eRykn8.js","assets/renderDocxPages-DIc2aiJB.js","assets/html2canvas.esm-B4CzG4On.js","assets/list-checks-vAkcDhTR.js","assets/shield-alert-BXGylg4Q.js","assets/grid-3x3-ClCYB6FB.js","assets/folder-open-CP9JKzSm.js","assets/file-image-DVvOGSQU.js","assets/file-spreadsheet-Q6qsWG3M.js","assets/file-code-CjRZc49M.js","assets/folder-Csf0S9zM.js","assets/MilestoneApproval-CrZ_4EPF.js","assets/LogDecisionDialog-Ci7GRGvs.js","assets/bell-BSliH8iT.js","assets/TranscriptAnalysisPanel-C7g24hOI.js","assets/alert-dialog-D6zmf4Qa.js","assets/zap-DC4LlnWT.js","assets/EngagementValueThread-DgBD8tae.js","assets/SOWUploadExtractor-
1Bwap4d86.js","assets/HistoricalFinancialsPanel-ATO1ETnB.js","assets/ClientPortalConfig-B63KYLfx.js","assets/chart-column-6WlVTHnt.js","assets/shield-BI9NGrnO.js","assets/mail-BWzQtSAz.js","assets/StatusReportComposer-1IrGYrTa.js","assets/PhasesMilestonesDialog-StKHFkEy.js","assets/TranscriptUploadDialog-CCZ8_aPY.js","assets/index-DWK1yKUm.js","assets/GranolaMeetingBrowser-BDUWnfl4.js","assets/settings-CFzYyjTl.js","assets/ProjectCompletionWizard-C4bVL-h2.js","assets/trophy-DDLL3U1f.js","assets/star-Bi_oSCUH.js","assets/clipboard-check-DG2jkXce.js","assets/TaskFormDialog-Djq2u4d8.js","assets/useFormPersistence-DFchkFzQ.js","assets/useEditConflictGuard-8dUM814i.js","assets/dictation-button-By6nIAA6.js","assets/ProjectFormDialog-kbV38KYF.js","assets/useRegions-Be2lEfLk.js","assets/useTerminology-Ci7zIKmj.js","assets/ConflictCheckDialog-BbdXi_mt.js","assets/file-warning-BppkjwTD.js","assets/folder-kanban-C52eeuLF.js","assets/globe-DQzIP_ik.js","assets/useEtcConfirmations-BfQ_j3Zp.js","assets/file-pen-CoG_T8rN.js","assets/timer-BobVofB4.js","assets/receipt-Fuhr8YYj.js","assets/calendar-check-BKyswPDE.js","assets/EditableField-A0jDiAtr.js","assets/index-BLdMKek_.js","assets/arrow-down-right-CZbhTnfW.js","assets/minus-CdxVbKUw.js","assets/useUserRole-DhLGHMgy.js","assets/expand-DtiOAWfU.js","assets/ProjectTimelinePanel-7gldqYYs.js","assets/SOWUploadToProjectDialog-CncU6ePC.js","assets/ChangeOrderDialog-mssk1FNb.js","assets/ProjectTemplateDialog-DBuNYn72.js"])))=>i.map(i=>d[i]); 2import{d as ze,s as N,b as jt,a0 as Ms,a7 as Zt,T as re,l as ne,m as ie,u as xe,D as st,e as at,f as rt,g as nt,h as ft,v as V,I as Ce,a4 as $e,L as Te,B as S,G as it,w as qe,x as Oe,y as et,z as Be,A as H,q as xt,k as O,a9 as es,n as vt,C as ct,a3 as $t,ab as Ds,F as Me,X as Ps,ac as Es,U as Rs,V as As,W as ke,Y as le,_ as B}from"./index-Epr9psQo.js";import{j as e}from"./vendor-radix-BnNg3BH5.js";import{r as c,i as Fs,d as Ls,h as $s,L as qs}from"./vendor-react-67mgcWXU.js";import{C as R,d as A,a as U,b as W,c as be}from"./card-DpKBVi42.js";import{B as T}from"./badge-Cl7apleB.js";import{P as je}from"./progress-OXAVVpg3.js";import{D as ht,a as pt,b as gt,e as ae,d as Os}from"./dropdown-menu-Duf4NJvQ.js";import{T as Bs}from"./TaskFormDialog-Djq2u4d8.js";import{P as Is}from"./ProjectFormDialog-kbV38KYF.js";import{M as Se,K as qt}from"./metric-DK0Tcl4m.js";import{a as Ne,u as _t,c as Ot}from"./vendor-query-PMAhJHCS.js";import{T as De}from"./trending-up-CXZcoU_y.js";import{B as zs}from"./bell-BSliH8iT.js";import{T as ge}from"./triangle-alert-C6ISfBPd.js";import{D as fe}from"./dollar-sign-CC-jyV1q.js";import{C as we}from"./clock-BYWbH6MV.js";import{U as bt}from"./users-uAR6_Qvs.js";import{T as ts}from"./trending-down-CFwiQb3W.js";import{C as ye}from"./circle-check-Cv8aCTuA.js";import{C as Hs}from"./circle-x-HEsvXgN2.js";import{f as Pe}from"./format-Bw8okCdv.js";import{a as Vs,i as Us}from"./useEtcConfirmations-BfQ_j3Zp.js";import{F as ss}from"./file-pen-CoG_T8rN.js";import{C as Ws}from"./calendar-clock-Dgofoxff.js";import{T as Ks}from"./timer-BobVofB4.js";import{G as as}from"./gauge-mfYImdAE.js";import{R as rs}from"./receipt-Fuhr8YYj.js";import{L as Gs}from"./link-2-Bu8oQt2W.js";import{C as Qs}from"./calendar-check-BKyswPDE.js";import{C as yt}from"./calendar-Ce69BthR.js";import{T as ns}from"./target-CyHaUH9t.js";import{C as Ys,a as Xs,b as Js}from"./collapsible-CKRfPF8i.js";import{A as Zs,m as is}from"./vendor-motion-CSzk-Fqg.js";import{T as ea,a as ta,b as Bt,c as Qe,d as sa,e as Ye}from"./table-023rHGnC.js";import{f as pe}from"./formatLabel-C4RR0vUw.js";import{S as lt}from"./separator-C2IB9E9R.js";import{S as aa}from"./shield-alert-BXGylg4Q.js";import{P as ls}from"./plus-DRTmwF2W.js";import{P as Nt}from"./pencil-PwBd4M7u.js";import{B as It}from"./brain-BAvvPRM1.js";import{S as cs}from"./sparkles-BcySMUTB.js";import{u as ra}from"./useRegions-Be2lEfLk.js";import{u as na}from"./useTerminology-Ci7zIKmj.js";import{E as ia}from"./EditableField-A0jDiAtr.js";import{L as os}from"./layers-ByEfk1Gr.js";import{G as la}from"./globe-DQzIP_ik.js";import{M as ds}from"./index-BMcbOcU5.js";import{r as ca}from"./index-BLdMKek_.js";import{S as ms,a as oa}from"./scroll-area-OnGFamwr.js";import{S as Ie}from"./skeleton-CXDkv5zX.js";import{A as _e}from"./activity-DehK1-wv.js";import{c as da}from"./constructNow-LutmP3uJ.js";import{i as ma}from"./isSameDay-YWnicZiN.js";import{s as ua}from"./subDays-O0YAIy_S.js";import{U as us}from"./upload-2-rh2XwF.js";import{M as xa}from"./message-square-7cL_4-It.js";import{i as ha}from"./isToday-ez2Bh_ph.js";import{C as pa}
2from"./copy-C-Qie2rJ.js";import{C as ga}from"./chevron-right-DQtszqux.js";import{L as xs}from"./list-todo-BS9RmsVo.js";import{A as ja}from"./arrow-up-right-zF0c4Zfm.js";import{A as fa}from"./arrow-down-right-CZbhTnfW.js";import{M as va}from"./minus-CdxVbKUw.js";import{u as _a}from"./useUserRole-DhLGHMgy.js";import{u as ba}from"./sidebar-BBoeMq0-.js";import{F as zt}from"./folder-kanban-C52eeuLF.js";import{A as Ht}from"./arrow-left-BKCvbsa9.js";import{E as ya}from"./ellipsis-C6BfvtHH.js";import{T as Na}from"./trophy-DDLL3U1f.js";import{E as Vt}from"./external-link-DnfaRxEP.js";import{S as wa}from"./scale-Cc_B3FHe.js";import{F as ka}from"./folder-open-CP9JKzSm.js";import{F as Ca}from"./flag-BJdgpYpl.js";import{M as Ut}from"./mic-eFw98pWv.js";import{E as Sa}from"./expand-DtiOAWfU.js";import{C as Wt}from"./circle-alert-CFN03ksH.js";import{P as hs}from"./pen-BjcYRxrI.js";/** 3 * @license lucide-react v0.462.0 - ISC 4 * 5 * This source code is licensed under the ISC license. 6 * See the LICENSE file in the root directory of this source tree. 7 */const Kt=ze("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** 8 * @license lucide-react v0.462.0 - ISC 9 * 10 * This source code is licensed under the ISC license. 11 * See the LICENSE file in the root directory of this source tree. 12 */const Ta=ze("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/** 13 * @license lucide-react v0.462.0 - ISC 14 * 15 * This source code is licensed under the ISC license. 16 * See the LICENSE file in the root directory of this source tree. 17 */const Ma=ze("Minimize",[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]);/** 18 * @license lucide-react v0.462.0 - ISC 19 * 20 * This source code is licensed under the ISC license. 21 * See the LICENSE file in the root directory of this source tree. 22 */const Da=ze("PanelTopClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m9 16 3-3 3 3",key:"1idcnm"}]]);/** 23 * @license lucide-react v0.462.0 - ISC 24 * 25 * This source code is licensed under the ISC license. 26 * See the LICENSE file in the root directory of this source tree. 27 */const Pa=ze("PanelTop",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}]]);function Ea(s){return ma(s,ua(da(s),1))}const wt={fixed_price:"Fixed Price",time_and_materials:"Time & Materials",retainer:"Retainer",milestone_based:"Milestone Based"};function tt(s){return s==="fixed_price"||s==="milestone_based"}function Ra(s){switch(s){case"fixed_price":case"retainer":case"milestone_based":return s;default:return"time_and_materials"}}function kt(s){return Ne({queryKey:["commercial-model",s],queryFn:async()=>{const{data:l,error:p}=await N.from("project_billing_policies").select("id, billing_model, fixed_price_amount, retainer_amount, retainer_billing_day, payment_terms_days").eq("project_id",s).maybeSingle();if(p)throw p;return{model:Ra(l?.billing_model),isDefaulted:!l,fixedPriceAmount:l?.fixed_price_amount??null,retainerAmount:l?.retainer_amount??null,retainerBillingDay:l?.retainer_billing_day??null,paymentTermsDays:l?.payment_terms_days??null,policyId:l?.id??null}},enabled:!!s})}function Aa({projectId:s,budget:l,projectTargetMargin:p,practiceId:h,completion:f=0,startDate:u}){const{currentTenant:r}=jt(),{data:n}=kt(s),[a,x]=c.useState(null),[i,t]=c.useState({effectiveTarget:35,alertThreshold:10,source:"org"}),[o,g]=c.useState(!0),[v,b]=c.useState(new Date),[d,m]=c.useState(!1),w=c.useCallback(async()=>{if(p!=null){t(k=>({...k,effectiveTarget:p,source:"project"}));return}if(h){const{data:k}=await N.from("practices").select("target_margin_percent").eq("id",h).single();if(k?.target_margin_percent!=null){t(M=>({...M,effectiveTarget:k.target_margin_percent,source:"practice"}));return}}if(r?.id){const{data:k}=await N.from("tenants").select("target_margin_percent, margin_alert_threshold").eq("id",r.id).single();k&&t({effectiveTarget:k.target_margin_percent??35,alertThreshold:k.margin_alert_threshold??10,source:"org"})}},[p,h,r?.id]);c.useEffect(()=>{w()},[w]);const E=c.useCallback(async()=>{try{const{data:k}=await N.from("time_entries").select(` 28 hours, 29 actual_minutes, 30 billable_minutes, 31 is_billable, 32 rate_override, 33 user_id, 34 profiles!time_entries_user_id_fkey(hourly_rate, profile_financials(hourly_cost)) 35 `).eq("project_id",s),{count:M}=await N.from("project_team_members").select("*",{count:"exact",head:!0}).eq("project_id",s);if(!k){x({totalRevenue:0,totalCost:0,grossMargin:0,marginPercent:0,hoursLogged:0,billableHours:0,teamMemberCount:M||0,budgetUsedPercent:0});return}let G=0,q=0,J=0,Z=0;for(const P of k){const ee=P.hours||(P.actual_minutes?P.actual_minutes/60:0),ve=P.billable_minutes?P.billable_minutes/60:P.is_billable?ee:0;if(J+=ee,P.is_billable){Z+=ve;const Ve=P.rate_override||P.profiles?.hourly_rate||0;G+=ve*Ve}const he=P.profiles?.profile_financials,Ee=(Array.isArray(he)?he[0]?.hourly_cost:he?.hourly_cost)||0;q+=ee*Ee}const Y=n?.model??"time_and_materials";let z=G,oe=l>0?Math.round(G/l*100):0;if(tt(Y)){const P=n?.fixedPriceAmount||l,ee=Math.min(Math.max(f,0),100)/100;z=P*ee,oe=P>0?Math.round(q/P*100):0}else if(Y==="retainer"&&n?.retainerAmount){const P=u?new Date(u):null,ee=new Date,ve=P&&P<=ee?Math.max((ee.getFullYear()-P.getFullYear())*12+(ee.getMonth()-P.getMonth())+1,1):1;z=n.retainerAmount*ve,oe=z>0?Math.round(q/z*100):0}const de=z-q,He=z>0?Math.round(de/z*100):0;x({totalRevenue:z,totalCost:q,grossMargin:de,marginPercent:He,hoursLogged:Math.round(J*10)/10,billableHours:Math.round(Z*10)/10,teamMemberCount:M||0,budgetUsedPercent:oe}),b(new Date)}catch(k){console.error("Error loading margin data:",k)}finally{g(!1)}},[s,l,n,f,u]),L=c.useCallback(async k=>
35{if(!d)try{const{data:M}=await N.from("tenant_members").select("user_id").eq("tenant_id",r?.id).in("role",["owner","admin"]);if(!M?.length)return;const{data:G}=await N.from("projects").select("name").eq("id",s).single(),q=i.effectiveTarget,J=q-k,Z=M.map(Y=>({user_id:Y.user_id,type:"alert",title:"Project Margin Alert",message:`Project "${G?.name}" is trending ${J}% below target margin (${k}% vs ${q}% target)`,link:`/projects/${s}`,metadata:{project_id:s,current_margin:k,target_margin:q,variance:J}}));await N.from("notifications").insert(Z),m(!0),Ms.info(`Margin alert sent for project ${s}`)}catch(M){console.error("Error sending margin alert:",M)}},[d,r?.id,s,i.effectiveTarget]);c.useEffect(()=>{if(!a||a.totalRevenue===0)return;const k=i.effectiveTarget,M=i.alertThreshold;k-a.marginPercent>=M&&!d&&L(a.marginPercent)},[a,i,d,L]),c.useEffect(()=>{E();const k=N.channel(`project-margin-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"time_entries",filter:`project_id=eq.${s}`},()=>{E()}).on("postgres_changes",{event:"*",schema:"public",table:"project_team_members",filter:`project_id=eq.${s}`},()=>{E()}).subscribe();return()=>{N.removeChannel(k)}},[s,E]);const C=k=>{const M=i.effectiveTarget;return k>=M+5?"text-success":k>=M-5?"text-primary":k>=M-15?"text-warning":"text-destructive"},j=k=>{const M=i.effectiveTarget;return k>=M+5?{variant:"excellent",label:"Excellent"}:k>=M-5?{variant:"good",label:"Healthy"}:k>=M-15?{variant:"at_risk",label:"Low"}:{variant:"critical",label:"Critical"}},_=k=>k>=1e6?`$${(k/1e6).toFixed(1)}M`:k>=1e3?`$${(k/1e3).toFixed(1)}K`:`$${k.toFixed(0)}`;if(o||!a)return e.jsx(R,{children:e.jsx(A,{className:"pt-6",children:e.jsxs("div",{className:"animate-pulse space-y-3",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-1/3"}),e.jsx("div",{className:"h-8 bg-muted rounded w-1/2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-full"})]})})});const I=j(a.marginPercent),$=i.effectiveTarget,Q=a.marginPercent<$,D=a.marginPercent<$-i.alertThreshold;return e.jsx(Zt,{children:e.jsxs(R,{className:D&&a.totalRevenue>0?"border-destructive/50":Q&&a.totalRevenue>0?"border-warning/50":"",children:[e.jsxs(U,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),"Live Margin Tracker"]}),n&&!n.isDefaulted&&e.jsx(T,{variant:"outline",className:"text-xs",children:wt[n.model]}),a.totalRevenue>0&&e.jsx(T,{variant:I.variant,children:I.label}),D&&a.totalRevenue>0&&e.jsxs(re,{children:[e.jsx(ne,{children:e.jsx(zs,{className:"h-4 w-4 text-destructive animate-pulse"})}),e.jsx(ie,{children:e.jsx("p",{children:"Management has been alerted"})})]})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Updated ",v.toLocaleTimeString()]})]}),e.jsxs(be,{className:"flex items-center gap-1",children:["Real-time profitability ⢠Target: ",$,"%",e.jsxs(re,{children:[e.jsx(ne,{children:e.jsx(T,{variant:"outline",className:"text-xs ml-1",children:i.source})}),e.jsx(ie,{children:e.jsxs("p",{children:["Target margin from ",i.source," level"]})})]})]})]}),e.jsxs(A,{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Se,{size:"md",className:C(a.marginPercent),children:[a.marginPercent,"%"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Gross Margin"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-semibold",children:_(a.grossMargin)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Profit"})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["vs ",$,"% target"]}),e.jsxs("span",{className:a.marginPercent>=$?"text-success":"text-warning",children:[a.marginPercent>=$?"+":"",a.marginPercent-$,"%"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(je,{value:Math.min(a.marginPercent,100),className:"h-2"}),e.jsx("div",{className:"absolute top-0 h-2 w-0.5 bg-foreground
35/50",style:{left:`${Math.min($,100)}%`}})]})]}),D&&a.totalRevenue>0&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(ge,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{children:["Margin critically low (",i.alertThreshold,"%+ below target). Management notified."]})]}),Q&&!D&&a.totalRevenue>0&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-warning/10 text-warning text-sm",children:[e.jsx(ge,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Margin below target. Consider team adjustments or scope review."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 pt-2 border-t",children:[e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center",children:e.jsx(fe,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:_(a.totalRevenue)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Revenue"})]})]})}),e.jsxs(ie,{children:[e.jsxs("p",{children:["Cost: ",_(a.totalCost)]}),e.jsxs("p",{children:["Profit: ",_(a.grossMargin)]})]})]}),e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center",children:e.jsx(we,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-medium",children:[a.hoursLogged,"h"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hours Logged"})]})]})}),e.jsxs(ie,{children:[e.jsxs("p",{children:["Billable: ",a.billableHours,"h"]}),e.jsxs("p",{children:["Utilization: ",a.hoursLogged>0?Math.round(a.billableHours/a.hoursLogged*100):0,"%"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center",children:e.jsx(bt,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:a.teamMemberCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Team Members"})]})]}),e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center",children:a.budgetUsedPercent>100?e.jsx(ts,{className:"h-4 w-4 text-destructive"}):e.jsx(De,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs("p",{className:`text-sm font-medium ${a.budgetUsedPercent>100?"text-destructive":""}`,children:[a.budgetUsedPercent,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n&&tt(n.model)?"Fee Consumed":n?.model==="retainer"?"Retainer Consumed":"Budget Used"})]})]})}),e.jsx(ie,{children:n&&tt(n.model)?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Cost: ",_(a.totalCost)]}),e.jsxs("p",{children:["Fee: ",_(n.fixedPriceAmount||l)]})]}):n?.model==="retainer"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Cost: ",_(a.totalCost)]}),e.jsxs("p",{children:["Recognized: ",_(a.totalRevenue)]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{children:["Revenue: ",_(a.totalRevenue)]}),e.jsxs("p",{children:["Budget: ",_(l)]})]})})]})]})]})]})})}const Gt={pending:{label:"Awaiting client",variant:"outline"},approved:{label:"Approved",variant:"default"},declined:{label:"Declined",variant:"destructive"},cancelled:{label:"Cancelled",variant:"secondary"}};function Fa({open:s,onOpenChange:l,projectId:p,currentBudget:h}){const{toast:f}=xe(),u=_t(),{currentTenant:r}=jt(),[n,a]=c.useState(""),[x,i]=c.useState(""),{data:t=[],isLoading:o}=Ne({queryKey:["budget-extension-requests",p],queryFn:async()=>{const{data:m,error:w}=await N.from("budget_extension_requests").select("id, additional_amount, current_budget, reason, status, client_note, decided_by_email, decided_at, created_at").eq("project_id",p).order("created_at",{ascending:!1});if(w)throw w;return m||[]},enabled:s&&!!p}),g=t.some(m=>m.status==="pending"),v=Ot({mutationFn:async()=>{const m=Number(n);if(!m||m<=0)throw new Error("Enter a positive extension amount");if(!r?.id)throw new Error("No active organization");const{data:w}=await N.auth.getUser(),{error:E}=await N.from("budget_extension_requests").insert({tenant_id:r.id,project_id:p,requested_by:w.user?.id??null,current_budget:h,additional_amount:m,reason:x.trim()||null});if(E)throw E},onSuccess:()=>{f({title:"Extension request sent",description:"The client will see it on their portal and can approve or decline."}
35),a(""),i(""),u.invalidateQueries({queryKey:["budget-extension-requests",p]})},onError:m=>{f({title:"Could not create request",description:m.message,variant:"destructive"})}}),b=Ot({mutationFn:async m=>{const{error:w}=await N.from("budget_extension_requests").update({status:"cancelled"}).eq("id",m).eq("status","pending");if(w)throw w},onSuccess:()=>{f({title:"Request cancelled"}),u.invalidateQueries({queryKey:["budget-extension-requests",p]})},onError:m=>{f({title:"Could not cancel request",description:m.message,variant:"destructive"})}}),d=m=>m.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return e.jsx(st,{open:s,onOpenChange:l,children:e.jsxs(at,{className:"max-w-lg",children:[e.jsxs(rt,{children:[e.jsx(nt,{children:"Budget Extension"}),e.jsx(ft,{children:"Request additional approved budget from the client. They decide directly on their portal, and an approval updates the project budget automatically."})]}),e.jsxs("div",{className:"space-y-4",children:[!g&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{htmlFor:"extension-amount",children:"Additional amount (USD)"}),e.jsx(Ce,{id:"extension-amount",type:"number",min:"1",step:"100",placeholder:"e.g. 25000",value:n,onChange:m=>a(m.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Current approved budget: ",d(h),Number(n)>0&&e.jsxs(e.Fragment,{children:[" â new total ",d(h+Number(n))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(V,{htmlFor:"extension-reason",children:"Reason shown to the client"}),e.jsx($e,{id:"extension-reason",placeholder:"Why is the extension needed? Scope additions, discovery findings, ...",value:x,onChange:m=>i(m.target.value),rows:3})]})]}),o?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx(Te,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):t.length>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Request history"}),t.map(m=>{const w=Gt[m.status]||Gt.pending;return e.jsxs("div",{className:"border rounded-md p-3 space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"font-medium text-sm",children:["+",d(m.additional_amount),e.jsxs("span",{className:"text-muted-foreground font-normal",children:[" ","on ",d(m.current_budget)]})]}),e.jsxs(T,{variant:w.variant,className:"text-xs",children:[m.status==="pending"&&e.jsx(we,{className:"h-3 w-3 mr-1"}),m.status==="approved"&&e.jsx(ye,{className:"h-3 w-3 mr-1"}),m.status==="declined"&&e.jsx(Hs,{className:"h-3 w-3 mr-1"}),w.label]})]}),m.reason&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.reason}),m.client_note&&e.jsxs("p",{className:"text-xs text-muted-foreground border-l-2 pl-2",children:["Client: ",m.client_note]}),e.jsxs("p",{className:"text-caption text-muted-foreground",children:["Requested ",Pe(new Date(m.created_at),"MMM d, yyyy"),m.decided_at&&m.decided_by_email&&e.jsxs(e.Fragment,{children:[" ⢠Decided by ",m.decided_by_email," on ",Pe(new Date(m.decided_at),"MMM d, yyyy")]})]}),m.status==="pending"&&e.jsx(S,{size:"sm",variant:"ghost",onClick:()=>b.mutate(m.id),disabled:b.isPending,children:"Cancel request"})]},m.id)})]}):null]}),e.jsxs(it,{children:[e.jsx(S,{variant:"outline",onClick:()=>l(!1),children:"Close"}),!g&&e.jsxs(S,{onClick:()=>v.mutate(),disabled:v.isPending||!Number(n),children:[v.isPending&&e.jsx(Te,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Send to Client"]})]})]})})}function ue(s){return Math.abs(s)>=1e6?`$${(s/1e6).toFixed(1)}M`:Math.abs(s)>=1e3?`$${(s/1e3).toFixed(1)}K`:`$${s.toFixed(0)}`}function La(s){return Ne({queryKey:["commercial-cockpit-entries",s],queryFn:async()=>{const{data:l,error:p}=await N.from("time_entries").select(` 36 hours, 37 actual_minutes, 38 billable_minutes, 39 is_billable, 40 rate_override, 41 invoice_id, 42 date, 43 profiles!time_entries_user_id_fkey(hourly_rate, profile_financials(hourly_cost)) 44 `).eq("project_id",s);if(p)throw p;const h=new Date,f=new Date(h.getFullYear(),h.getMonth(),1),u=7*24*60*60*1e3,r={totalHours:0,billableHours:0,billedValue:0,unbilledWip:0,totalCost:0,costThisMonth:0,hoursThisMonth:0,weeklyBurn:[0,0,0,0],weeklyCost:[0,0,0,0]};for(const n of l||[]){const a=n.profiles,x=n.hours||(n.actual_minutes?n.actual_minutes/60:0),i=n.billable_minutes?n.billable_minutes/60:n.is_billable?x:0,t=n.rate_override||a?.hourly_rate||0,o=a?.profile_financials,v=((Array.isArray(o)?o[0]?.hourly_cost:o?.hourly_cost)||0)*x,b=n.is_billable?i*t:0;r.totalHours+=x,r.totalCost+=v,n.is_billable&&(r.billableHours+=i,r.billedValue+=b,n.invoice_id||(r.unbilledWip+=b));const d=new Date(n.date);d>=f&&(r.costThisMonth+=v,r.hoursThisMonth+=x);const m=Math.floor((h.getTime()-d.getTime())/u);m>=0&&m<4&&(r.weeklyBurn[m]+=b,r.weeklyCost[m]+=v)}return r},enabled:!!s})}function se({label:s,value:l,sub:p,danger:h}){return e.jsxs("div",{children:[e.jsx("p",{className:`text-lg font-semibold ${h?"text-destructive":""}`,children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s}),p&&e.jsx("p",{className:"text-caption text-muted-foreground",children:p})]})}function $a({projectId:s,budget:l,completion:p,targetMargin:h,onOpenChangeOrders:f}){const{data:u,isLoading:r}=kt(s),{data:n,isLoading:a}=La(s),{data:x}=Vs(s),[i,t]=c.useState(!1);if(r||a||!u||!n)return e.jsx(R,{children:e.jsx(A,{className:"pt-6",children:e.jsxs("div",{className:"animate-pulse space-y-3",children:[e.jsx("div",{className:"h-4 bg-muted rounded w-1/3"}),e.jsx("div",{className:"h-8 bg-muted rounded w-1/2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-full"})]})})});const o=wt[u.model];if(tt(u.model)){const C=u.fixedPriceAmount||l,j=n.totalCost,_=Math.min(Math.max(p,0),100)/100,I=n.totalHours>0?n.totalCost/n.totalHours:0,$=!!x&&x.confirmedTaskCount>0&&I>0,Q=$&&!!x.oldestConfirmation&&Us(x.oldestConfirmation),D=_>0?Math.max(j/_-j,0):null;let k,M,G;if($){const{confirmedTaskCount:z,openTaskCount:oe,totalRemainingHours:de}=x,He=de*I,P=Math.max(oe-z,0);let ee=0;P>0&&(ee=D!=null?D*(P/oe):de/z*P*I),M=He+ee,k=j+M,G=`${z}/${oe} task ETCs confirmed (${Math.round(de)}h)${P>0?` + estimate for ${P} unconfirmed`:""}${Q?" â some stale":""}`}else M=D,k=D!=null?j+D:null,G=_===0?"Set completion % to forecast":"Velocity-based â no confirmed task ETCs yet";const q=C>0&&k!=null?(C-k)/C*100:null,J=C>0?(C*_-j)/Math.max(C*_,1)*100:null,Z=C>0?j/C*100:0,Y=q!=null&&q<h;return e.jsxs(R,{className:Y?"border-warning/50":"",children:[e.jsxs(U,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(fe,{className:"h-4 w-4"}),"Fixed-Price Cockpit"]}),e.jsx(T,{variant:"outline",children:o})]}),e.jsx(be,{children:"Fee-anchored economics â every saved hour is margin"})]}),e.jsxs(A,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(se,{label:"Contract Fee",value:ue(C)}),e.jsx(se,{label:"Cost to Date",value:ue(j),sub:`${Math.round(n.totalHours)}h logged`}),e.jsx(se,{label:"Est. to Complete",value:M!=null?ue(M):"â",sub:G}),e.jsx(se,{label:"Projected Margin",value:q!=null?`${Math.round(q)}%`:"â",sub:`Target ${h}%`,danger:Y})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Fee consumed by cost"}),e.jsxs("span",{className:Z>100?"text-destructive":"",children:[Math.round(Z),"%"]})]}),e.jsx(je,{value:Math.min(Z,100),className:"h-2"})]}),J!=null&&_>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Margin on work delivered so far: ",Math.round(J),"%"]}),Y&&e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 rounded-md bg-warning/10 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-warning",children:[e.jsx(ge,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Projected margin below target â review scope or staffing."})]}),f&&e.jsxs(S,{size:"sm",variant:"outline",onClick:f,children:[e.jsx(ss,{className:"h-3.5 w-3.5 mr-1.5"}),"Change Order"]})]})]})]})}if(u.model==="retainer"){const C=u.retainerAmount||0,j=n.hoursThisMonth>0?C/n.hoursThisMonth:null,_=C>0?(C-n.costThisMonth)/C*100:null,I=_!=null&&_<h;return e.jsxs(R,{className:I?"border-warning/50":"",children:[e.jsxs(U,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(Ws,{className:"h-4 w-4"}),"Retainer Cockpit"]}),e.jsx(T,{variant:"outline",children:o})]}),e.jsx(be,{children:"This month's retainer economics"})]}),e.jsxs(A,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(se,{label:"Monthly Retainer",value:C>0?ue(C):"â"}),e.jsx(se,{label:"Hours This Month",value:`${Math.round(n.hoursThisMonth*10)/10}h`}),e.jsx(se,{label:"Cost This Month",value:ue(n.costThisMonth)}),e.jsx(se,{label:"Effective Rate",value:j!=null?`$${Math.round(j)}/h`:"â",sub:_!=null?`${Math.round(_)}% margin this month`:void 0,danger:I})]}),I&&e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-warning/10 text-warning text-sm",children:[e.jsx(ge,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"This month's margin is below target â hours are outpacing the retainer."})]})]})]})}const g=l>0?n.billedValue/l*100:0,v=Math.max(l-n.billedValue,0),b=n.weeklyBurn.filter(C=>C>0),d=b.length>0?n.weeklyBurn.reduce((C,j)=>C+j,0)/Math.max(b.length,1):0,m=d>0&&l>0?v/d:null,w=m!=null?new Date(Date.now()+m*7*24*60*60*1e3):null,E=n.totalHours>0?n.billableHours/n.totalHours*100:0,L=l>0&&g>=85;return e.jsxs(R,{className:L?"border-warning/50":"",children:[e.jsxs(U,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"T&M Cockpit"]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(T,{variant:"outline",children:o}),u.isDefaulted&&e.jsx(T,{variant:"secondary",children:"assumed"})]})]}),e.jsx(be,{children:"Budget runway, unbilled WIP, and realization"})]}),e.jsxs(A,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(se,{label:"Billed Value",value:ue(n.billedValue),sub:l>0?`of ${ue(l)} approved`:"No approved budget set"}),e.jsx(se,{label:"Unbilled WIP",value:ue(n.unbilledWip),sub:"Billable work not yet invoiced"}),e.jsx(se,{label:"Runway",value:m!=null?m>52?">1 year":`${Math.round(m*10)/10} wks`:"â",sub:w&&m!=null&&m<=52?`Budget exhausted ~${w.toLocaleDateString()}`:d===0?"No burn in last 4 weeks":void 0,danger:m!=null&&m<4}),e.jsx(se,{label:"Realization",value:`${Math.round(E)}%`,sub:"Billable share of hours logged",danger:n.totalHours>0&&E<70})]}),l>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(as,{className:"h-3.5 w-3.5"}
44)," Budget consumed"]}),e.jsxs("span",{className:g>100?"text-destructive":"",children:[Math.round(g),"%"]})]}),e.jsx(je,{value:Math.min(g,100),className:"h-2"})]}),L&&e.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 rounded-md bg-warning/10 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-warning",children:[e.jsx(ge,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Approaching the approved budget â time to update the client and discuss an extension."})]}),e.jsxs(S,{size:"sm",variant:"outline",onClick:()=>t(!0),children:[e.jsx(Kt,{className:"h-3.5 w-3.5 mr-1.5"}),"Request Extension"]})]}),!L&&e.jsxs(S,{size:"sm",variant:"ghost",className:"text-muted-foreground",onClick:()=>t(!0),children:[e.jsx(Kt,{className:"h-3.5 w-3.5 mr-1.5"}),"Request budget extension"]}),e.jsx(Fa,{open:i,onOpenChange:t,projectId:s,currentBudget:l}),n.unbilledWip>0&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(rs,{className:"h-3.5 w-3.5"}),ue(n.unbilledWip)," of delivered work is awaiting invoicing."]})]})]})}const qa={pending:"bg-muted text-muted-foreground",due:"bg-warning/15 text-warning border-warning/30",invoiced:"bg-success/15 text-success border-success/30"};function Oa(s){return s.invoice_amount!=null?`$${s.invoice_amount.toLocaleString()}`:s.invoice_pct!=null?`${s.invoice_pct}% of fee`:"â"}function Ba({projectId:s}){const l=_t(),[p,h]=c.useState(null),{data:f}=Ne({queryKey:["milestone-billing-schedule",s],queryFn:async()=>{const{data:a,error:x}=await N.from("project_billing_schedule").select("id, schedule_item_name, trigger_type, trigger_milestone_id, trigger_date, invoice_amount, invoice_pct, status, due_date, invoiced_at").eq("project_id",s).order("created_at");if(x)throw x;return a||[]},enabled:!!s}),{data:u}=Ne({queryKey:["milestone-billing-milestones",s],queryFn:async()=>{const{data:a,error:x}=await N.from("phases").select("id").eq("project_id",s);if(x)throw x;if(!a?.length)return[];const{data:i,error:t}=await N.from("milestones").select("id, name, status").in("phase_id",a.map(o=>o.id)).order("sort_order");if(t)throw t;return i||[]},enabled:!!s});if(!f||f.length===0)return null;const r=new Map((u||[]).map(a=>[a.id,a])),n=async(a,x)=>{h(a.id);try{const i=x==="none"?null:x;let t=null;if(i){const{data:v,error:b}=await N.from("milestones").select("status").eq("id",i).single();if(b)throw b;t=v?.status??null}const o={trigger_milestone_id:i,trigger_type:i?"milestone":"manual"};a.status==="pending"&&t==="completed"&&(o.status="due",o.due_date=new Date().toISOString().slice(0,10));const{error:g}=await N.from("project_billing_schedule").update(o).eq("id",a.id);if(g)throw g;l.invalidateQueries({queryKey:["milestone-billing-schedule",s]}),l.invalidateQueries({queryKey:["milestone-billing-milestones",s]}),o.status==="due"?xt.success("That milestone is already complete â the payment is now marked due for the next billing run."):xt.success(i?"Payment linked to milestone":"Milestone link removed")}catch{xt.error("Failed to update schedule item")}finally{h(null)}};return e.jsxs(R,{children:[e.jsxs(U,{className:"pb-2",children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4"}),"Billing Schedule"]}),e.jsx(be,{children:"Link payments to delivery milestones â completing a linked milestone marks its payment due for the next billing run."})]}),e.jsx(A,{className:"space-y-2",children:f.map(a=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-md border p-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.schedule_item_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Oa(a),a.due_date&&a.status==="due"&&` · due ${Pe(new Date(a.due_date),"MMM d")}`,a.invoiced_at&&` · invoiced ${Pe(new Date(a.invoiced_at),"MMM d")}`]})]}),e.jsx(T,{variant:"outline",className:qa[a.status]||"",children:a.status}),a.status==="pending"?e.jsxs(qe,{value:a.trigger_milestone_id||"none",onValueChange:x=>n(a,x),disabled:p===a.id,children:[e.jsxs(Oe,{className:"h-7 w-[180px] text-xs","aria-label":`Trigger milestone for ${a.schedule_item_name}`,children:[e.jsx(Gs,{className:"h-3 w-3 mr-1 flex-shrink-0"}),e.jsx(et,{placeholder:"Link milestone"})]}),e.jsxs(Be,{children:[e.jsx(H,{value:"none",children:"No milestone"}),(u||[]).map(x=>e.jsxs(H,{value:x.id,children:[x.name,x.status==="completed"?" (done)":""]},x.id))]})]}):a.trigger_milestone_id&&r.get(a.trigger_milestone_id)?e.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Qs,{className:"h-3 w-3"}),r.get(a.trigger_milestone_id).name]}):null]},a.id))})]})}function Ia({projectId:s,budget:l,totalCost:p,totalRevenue:h,marginPercent:f,targetMargin:u}){const[r,n]=c.useState(null),a=c.useCallback(async()=>{try{const i=new Date;i.setDate(i.getDate()-14);const t=new Date;t.setDate(t.getDate()-7);const{data:o}=await N.from("time_entries").select(` 45 hours, actual_minutes, is_billable, billable_minutes, 46 rate_override, date, 47 profiles!time_entries_user_id_fkey(hourly_rate, profile_financials(hourly_cost)) 48 `).eq("project_id",s).gte("date",i.toISOString().split("T")[0]);if(!o||o.length===0){n(null);return}let g=0,v=0,b=0,d=0;for(const D of o){const k=new Date(D.date),M=D.hours||(D.actual_minutes?D.actual_minutes/60:0),G=D.billable_minutes?D.billable_minutes/60:D.is_billable?M:0,q=D.profiles?.profile_financials,J=(Array.isArray(q)?q[0]?.hourly_cost:q?.hourly_cost)||0,Z=D.rate_override||D.profiles?.hourly_rate||0,Y=M*J,z=D.is_billable?G*Z:0;k<t?(g+=Y,v+=z):(b+=Y,d+=z)}const m=(g+b)/2,w=(v+d)/2,E=Math.max(l-h,0),L=w>0?E/w:1/0,C=h+w*Math.min(L,52),j=p+m*Math.min(L,52),_=C>0?Math.round((C-j)/C*100):0,I=v>0?(v-g)/v:0,$=d>0?(d-b)/d:0,Q=$>I+.02?"improving":$<I-.02?"declining":"stable";n({weeklyBurnRate:m,weeklyRevenueRate:w,budgetRunwayWeeks:Math.round(L*10)/10,projectedCompletionWeeks:Math.round(L*10)/10,projectedFinalMargin:_,trendDirection:Q})}catch(i){console.error("Error loading forecast:",i)}}
48,[s,l,p,h]);if(c.useEffect(()=>{a()},[a]),!r||r.weeklyBurnRate===0)return null;const x=i=>i>=1e3?`$${(i/1e3).toFixed(1)}K`:`$${i.toFixed(0)}`;return e.jsx(Zt,{children:e.jsxs("div",{className:"flex items-center gap-4 px-4 py-2 bg-muted/30 border rounded-lg text-sm flex-wrap",children:[e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(as,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Burn:"}),e.jsxs("span",{className:"font-medium",children:[x(r.weeklyBurnRate),"/wk"]})]})}),e.jsx(ie,{children:"Average weekly cost over last 2 weeks"})]}),e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(yt,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Runway:"}),e.jsx("span",{className:O("font-medium",r.budgetRunwayWeeks<4?"text-destructive":r.budgetRunwayWeeks<8?"text-warning":"text-foreground"),children:r.budgetRunwayWeeks===1/0?"â":`${r.budgetRunwayWeeks}wk`})]})}),e.jsx(ie,{children:"Weeks of budget remaining at current pace"})]}),e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ns,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Proj. Margin:"}),e.jsxs("span",{className:O("font-medium",r.projectedFinalMargin>=u?"text-success":r.projectedFinalMargin>=u-10?"text-warning":"text-destructive"),children:[r.projectedFinalMargin,"%"]})]})}),e.jsx(ie,{children:"Projected final margin based on current trajectory"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(De,{className:O("h-3.5 w-3.5",r.trendDirection==="improving"?"text-success":r.trendDirection==="declining"?"text-destructive":"text-muted-foreground")}),e.jsx("span",{className:O("text-xs capitalize",r.trendDirection==="improving"?"text-success":r.trendDirection==="declining"?"text-destructive":"text-muted-foreground"),children:r.trendDirection})]})]})})}function za({projectId:s}){const{toast:l}=xe(),[p,h]=c.useState([]),[f,u]=c.useState(!0),[r,n]=c.useState(!0);c.useEffect(()=>{a()},[s]);const a=async()=>{try{const{data:o,error:g}=await N.from("scope_creep_alerts").select("*, tasks(title)").eq("project_id",s).is("acknowledged_at",null).order("variance_percent",{ascending:!1});if(g)throw g;h(o||[])}catch(o){console.error("Error loading scope creep alerts:",o)}finally{u(!1)}},x=async o=>{const{error:g}=await N.from("scope_creep_alerts").update({acknowledged_at:new Date().toISOString()}).eq("id",o);if(g){l({title:"Error",description:"Failed to acknowledge alert",variant:"destructive"});return}h(v=>v.filter(b=>b.id!==o)),l({title:"Alert acknowledged"})};if(f||p.length===0)return null;const i=p.filter(o=>o.alert_type==="critical").length,t=p.filter(o=>o.alert_type==="warning").length;return e.jsx(R,{className:`border-l-4 ${i>0?"border-l-red-500":"border-l-amber-500"}`,children:e.jsxs(Ys,{open:r,onOpenChange:n,children:[e.jsx(Xs,{asChild:!0,children:e.jsx(U,{className:"cursor-pointer hover:bg-muted/50 transition-colors py-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(ge,{className:`h-4 w-4 ${i>0?"text-destructive":"text-warning"}`}),"Scope Creep Alerts",e.jsxs("div",{className:"flex items-center gap-1.5 ml-2",children:[i>0&&e.jsxs(T,{variant:"destructive",className:"text-xs",children:[i," critical"]}),t>0&&e.jsxs(T,{variant:"secondary",className:"text-xs bg-warning/10 text-warning",children:[t," warning"]})]})]}),r?e.jsx(es,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(vt,{className:"h-4 w-4 text-muted-foreground"})]})})}),e.jsx(Js,{children:e.jsx(A,{className:"pt-0 pb-3",children:e.jsx("div",{className:"space-y-2",children:e.jsx(Zs,{mode:"popLayout",children:p.map(o=>{const g=o.estimated_minutes/60,v=o.actual_minutes/60,b=Math.min(o.actual_minutes/o.estimated_minutes*100,150);return e.jsx(is.div,{initial:{opacity:0,height:0}
48,animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:`p-3 rounded-lg border ${o.alert_type==="critical"?"bg-destructive/5 border-destructive/30":"bg-warning/5 border-warning/30"}`,children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.tasks?.title||"Task"}),e.jsxs(T,{variant:"outline",className:`text-caption ${o.alert_type==="critical"?"text-destructive border-destructive/50":"text-warning border-warning/50"}`,children:["+",o.variance_percent.toFixed(0),"% over"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mb-2",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(we,{className:"h-3 w-3"}),"Est: ",g.toFixed(1),"h"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(De,{className:"h-3 w-3"}),"Actual: ",v.toFixed(1),"h"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(je,{value:Math.min(b,100),className:`h-1.5 ${o.alert_type==="critical"?"[&>div]:bg-destructive":"[&>div]:bg-warning"}`}),b>100&&e.jsx("div",{className:"absolute top-0 h-1.5 bg-destructive/50 rounded-r",style:{left:"100%",width:`${Math.min((b-100)*.5,50)}%`}})]})]}),e.jsxs(S,{variant:"ghost",size:"sm",className:"h-7 text-xs shrink-0",onClick:()=>x(o.id),children:[e.jsx(ct,{className:"h-3 w-3 mr-1"}),"Ack"]})]})},o.id)})})})})})]})})}const Qt={critical:"bg-destructive text-destructive-foreground",high:"bg-warning/15 text-warning border-warning/30",medium:"bg-warning/15 text-warning border-warning/30",low:"bg-muted text-muted-foreground"},Yt={open:"bg-destructive/10 text-destructive border-destructive/30",mitigating:"bg-warning/15 text-warning border-warning/30",resolved:"bg-success/15 text-success border-success/30",accepted:"bg-muted text-muted-foreground"};function Ha({projectId:s,tenantId:l}){const{toast:p}=xe(),h=_t(),[f,u]=c.useState(!1),[r,n]=c.useState(null),[a,x]=c.useState(!1),[i,t]=c.useState({title:"",description:"",severity:"",mitigation:"",category:""}),[o,g]=c.useState({title:"",description:"",severity:"medium",mitigation:"",category:""}),{data:v=[],isLoading:b}=Ne({queryKey:["project-risks",s],queryFn:async()=>{const{data:j,error:_}=await N.from("project_risks").select("*").eq("project_id",s).order("created_at",{ascending:!1});if(_)throw _;return j||[]}}),d=async()=>{if(o.title.trim())try{const{error:j}=await N.from("project_risks").insert({project_id:s,tenant_id:l,title:o.title,description:o.description||null,severity:o.severity,mitigation:o.mitigation||null,category:o.category||null,source:"manual",status:"open"});if(j)throw j;p({title:"Risk added"}),u(!1),g({title:"",description:"",severity:"medium",mitigation:"",category:""}),h.invalidateQueries({queryKey:["project-risks",s]})}catch{p({title:"Failed to add risk",variant:"destructive"})}},m=async(j,_)=>{try{const{error:I}=await N.from("project_risks").update({status:_}).eq("id",j);if(I)throw I;h.invalidateQueries({queryKey:["project-risks",s]}),r?.id===j&&n($=>$?{...$,status:_}:null)}catch{p({title:"Failed to update status",variant:"destructive"})}},w=j=>{n(j),x(!1)},E=()=>{r&&(t({title:r.title||"",description:r.description||"",severity:r.severity||"medium",mitigation:r.mitigation||"",category:r.category||""}),x(!0))},L=async()=>{if(!(!r||!i.title.trim()))try{const{error:j}=await N.from("project_risks").update({title:i.title,description:i.description||null,severity:i.severity,mitigation:i.mitigation||null,category:i.category||null}).eq("id",r.id);if(j)throw j;p({title:"Risk updated"}),n(_=>_?{..._,...i}:null),x(!1),h.invalidateQueries({queryKey:["project-risks",s]})}catch{p({title:"Failed to update risk",variant:"destructive"})}},C=v.filter(j=>j.status!=="resolved");return b?null:e.jsxs(e.Fragment,{children:[e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(aa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(W,{className:"text-sm font-medium",children:"Risk Register"}),C.length>0&&e.jsxs(T,{variant:"secondary",className:"text-caption",children:[C.length," open"]})]}),e.jsxs(S,{variant:"outline",size:"sm",onClick:()=>u(!0),children:[e.jsx(ls,{className:"h-3 w-3 mr-1"})," Add Risk"]})]})}),e.jsx(A,{className:"pt-0",children:v.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No risks identified yet. Add risks manually or they'll be extracted from transcript analysis."}):e.jsxs(ea,{children:[e.jsx(ta,{children:e.jsxs(Bt,{children:[e.jsx(Qe,{className:"text-xs",children:"Risk"}),e.jsx(Qe,{className:"text-xs w-[80px]",children:"Severity"}),e.jsx(Qe,{className:"text-xs w-[90px]",children:"Status"}),e.jsx(Qe,{className:"text-xs w-[80px]",children:"Source"})]})}),e.jsx(sa,{children:v.map(j=>e.jsxs(Bt,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>w(j),children:[e.jsx(Ye,{children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:j.title}),j.description&&e.jsx("p",{className:"text-caption text-muted-foreground mt-0.5 line-clamp-1",children:j.description}),j.mitigation&&e.jsxs("p",{className:"text-caption text-success mt-0.5 line-clamp-1",children:["Mitigation: ",j.mitigation]})]})}),e.jsx(Ye,{children:e.jsx(T,{variant:"outline",className:O("text-caption",Qt[j.severity]),children:pe(j.severity)})}),e.jsx(Ye,{onClick:_=>_.stopPropagation(),children:e.jsxs(qe,{value:j.status,onValueChange:_=>m(j.id,_),children:[e.jsx(Oe,{className:"h-6 text-caption w-[80px]",children:e.jsx(T,{variant:"outline",className:O("text-caption",Yt[j.status]),children:pe(j.status)})}),e.jsxs(Be,{children:[e.jsx(H,{value:"open",children:"Open"}),e.jsx(H,{value:"mitigating",children:"Mitigating"}),e.jsx(H,{value:"resolved",children:"Resolved"}),e.jsx(H,{value:"accepted",children:"Accepted"})]})]})}),e.jsx(Ye,{children:e.jsx(T,{variant:"secondary",className:"text-caption",children:pe(j.source||"manual")})})]},j.id))})]})})]}),e.jsx(st,{open:f,onOpenChange:u,children:e.jsxs(at,{children:[e.jsx(rt,{children:e.jsx(nt,{children:"Add Risk"})}),e.jsx($t,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Title"}),e.jsx(Ce,{value:o.title,onChange:j=>g(_=>({..._,title:j.target.value})),placeholder:"e.g. Resource availability risk"})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Description"}),e.jsx($e,{value:o.description,onChange:j=>g(_=>({..._,description:j.target.value})),placeholder:"Describe the risk...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Severity"}),e.jsxs(qe,{value:o.severity,onValueChange:j=>g(_=>({..._,severity:j})),children:[e.jsx(Oe,{children:e.jsx(et,{})}),e.jsxs(Be,{children:[e.jsx(H,{value:"low",children:"Low"}),e.jsx(H,{value:"medium",children:"Medium"}),e.jsx(H,{value:"high",children:"High"}),e.jsx(H,{value:"critical",children:"Critical"})]})]})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Category"}),e.jsx(Ce,{value:o.category,onChange:j=>g(_=>({..._,category:j.target.value})),placeholder:"e.g. Staffing, Technical"})]})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Mitigation"}),e.jsx($e,{value:o.mitigation,onChange:j=>g(_=>({..._,mitigation:j.target.value})),placeholder:"Mitigation plan...",rows:2})]})]})}),e.jsxs(it,{children:[e.jsx(S,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(S,{onClick:d,disabled:!o.title.trim(),children:"Add Risk"})]})]})}),e.jsx(st,{open:!!r,onOpenChange:j=>{j||(n(null),x(!1))},children:e.jsxs(at,{className:"max-w-xl",children:[e.jsxs(rt,{children:[e.jsxs("div",{className:"flex items-center justify-between pr-6",children:[e.jsx(nt,{className:"text-base",children:a?"Edit Risk":"Risk Details"}),!a&&r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(T,{variant:"outline",className:O("text-xs",Qt[r.severity]),children:pe(r.severity)}),e.jsx(T,{variant:"outline",className:O("text-xs",Yt[r.status]),children:pe(r.status)})]})]}),e.jsx(ft,{className:"sr-only",children:"View and edit risk details"})]}),e.jsxs($t,{children:[r&&!a&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold",children:r.title}),r.category&&e.jsx(T,{variant:"secondary",className:"text-caption mt-1",children:r.category})]}),r.description&&e.jsxs("div",{children:[e.jsx(V,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:r.description})]}),e.jsx(lt,{}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs text-muted-foreground",children:"Mitigation Strategy"}),r.mitigation?e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:r.mitigation}):e.jsx("p",{className:"text-sm mt-1 text-muted-foreground italic",children:"No mitigation strategy documented yet."})]}),e.jsx(lt,{}),e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-xs",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs text-muted-foreground",children:"Source"}),e.jsx("p",{className:"mt-0.5 font-medium",children:pe(r.source||"manual")})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs text-muted-foreground",children:"Status"}),e.jsx("div",{className:"mt-0.5",children:e.jsxs(qe,{value:r.status,onValueChange:j=>m(r.id,j),children:[e.jsx(Oe,{className:"h-7 text-xs w-full",children:e.jsx(et,{})}),e.jsxs(Be,{children:[e.jsx(H,{value:"open",children:"Open"}),e.jsx(H,{value:"mitigating",children:"Mitigating"}),e.jsx(H,{value:"resolved",children:"Resolved"}),e.jsx(H,{value:"accepted",children:"Accepted"})]})]})})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs text-muted-foreground",children:"Identified"}),e.jsx("p",{className:"mt-0.5 font-medium",children:r.created_at?new Date(r.created_at).toLocaleDateString():"â"})]})]})]}),r&&a&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Title"}),e.jsx(Ce,{value:i.title,onChange:j=>t(_=>({..._,title:j.target.value}))})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Description"}),e.jsx($e,{value:i.description,onChange:j=>t(_=>({..._,description:j.target.value})),rows:3})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Severity"}),e.jsxs(qe,{value:i.severity,onValueChange:j=>t(_=>({..._,severity:j})),children:[e.jsx(Oe,{children:e.jsx(et,{})}),e.jsxs(Be,{children:[e.jsx(H,{value:"low",children:"Low"}),e.jsx(H,{value:"medium",children:"Medium"}),e.jsx(H,{value:"high",children:"High"}),e.jsx(H,{value:"critical",children:"Critical"})]})]})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Category"}),e.jsx(Ce,{value:i.category,onChange:j=>t(_=>({..._,category:j.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(V,{className:"text-xs",children:"Mitigation Strategy"}),e.jsx($e,{value:i.mitigation,onChange:j=>t(_=>({..._,mitigation:j.target.value})),rows:4,placeholder:"Document the full mitigation plan..."})]})]})]}),e.jsx(it,{children:a?e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(S,{onClick:L,disabled:!i.title.trim(),children:"Save Changes"})]}):e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"outline",onClick:()=>n(null),children:"Close"}),e.jsxs(S,{onClick:E,children:[e.jsx(Nt,{className:"h-3 w-3 mr-1"})," Edit"]})]})})]})})]})}function Va({projectId:s,projectName:l,projectStatus:p,className:h}){const{currentTenant:f}=jt(),{toast:u}=xe(),[r,n]=c.useState(!1),[a,x]=c.useState(!1),[i,t]=c.useState(null),o=async()=>
48{if(f?.id){x(!0),t(null);try{const{data:g,error:v}=await N.functions.invoke("learn-from-outcome",{body:{event_type:"project_completed",source_id:s,tenant_id:f.id}});if(v)throw v;t({lessonsExtracted:g?.patterns_found||0,patternsDetected:g?.patterns_found||0,wikiSuggestions:g?.wiki_suggestions||0}),u({title:"Learning complete",description:`Extracted ${g?.patterns_found||0} patterns from this project`})}catch(g){console.error("Error learning from project:",g),u({title:"Error",description:"Failed to extract learnings. Please try again.",variant:"destructive"})}finally{x(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs(S,{variant:"outline",size:"sm",className:h,onClick:()=>n(!0),children:[e.jsx(It,{className:"h-4 w-4 mr-1.5"}),"Learn from This"]}),e.jsx(st,{open:r,onOpenChange:n,children:e.jsxs(at,{className:"sm:max-w-md",children:[e.jsxs(rt,{children:[e.jsxs(nt,{className:"flex items-center gap-2",children:[e.jsx(It,{className:"h-5 w-5 text-primary"}),"Extract Learnings"]}),e.jsxs(ft,{children:['Analyze "',l,'" to extract patterns, lessons, and insights that can improve future projects.']})]}),e.jsxs("div",{className:"py-4",children:[!a&&!i&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will analyze the project to:"}),e.jsxs("ul",{className:"space-y-2 text-sm",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),"Extract lessons learned from tasks and decisions"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),"Identify estimation patterns (scope creep, accuracy)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),"Suggest wiki articles for reusable knowledge"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),"Index insights for future AI recommendations"]})]})]}),a&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8",children:[e.jsx(Te,{className:"h-8 w-8 animate-spin text-primary mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Analyzing project patterns..."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This may take a moment"})]}),i&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-success mb-4",children:[e.jsx(ct,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:"Analysis Complete"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"text-center p-3 rounded-lg bg-muted/50",children:[e.jsx(Se,{size:"md",children:i.lessonsExtracted}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Lessons"})]}),e.jsxs("div",{className:"text-center p-3 rounded-lg bg-muted/50",children:[e.jsx(Se,{size:"md",children:i.patternsDetected}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Patterns"})]}),e.jsxs("div",{className:"text-center p-3 rounded-lg bg-muted/50",children:[e.jsx(Se,{size:"md",children:i.wikiSuggestions}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Wiki Ideas"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center mt-4",children:"These insights will improve AI recommendations for future projects."})]})]}),e.jsx(it,{children:i?e.jsx(S,{onClick:()=>n(!1),children:"Done"}):e.jsxs(e.Fragment,{children:[e.jsx(S,{variant:"outline",onClick:()=>n(!1),disabled:a,children:"Cancel"}),e.jsx(S,{onClick:o,disabled:a,children:a?e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"h-4 w-4 mr-2 animate-spin"}),"Analyzing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"h-4 w-4 mr-2"}),"Extract Learnings"]})})]})})]})})]})}const Ua=["Strategy","Implementation","Advisory","Assessment","Training","Other"],Xt=[{value:"excellent",label:"Excellent"},{value:"good",label:"On Track"},{value:"on_track",label:"On Track"},{value:"at_risk",label:"At Risk"},{value:"critical",label:"Critical"}];function Wa({project:s,onUpdate:l}){const{toast:p}=xe(),{regions:h}=ra(),{practices:f}=Ds(),{projectLabel:u}=na(),r=async(i,t)=>{const{error:o}=await N.from("projects").update({[i]:t}).eq("id",s.id);o?p({title:"Error updating "+i,variant:"destructive"}):(p({title:`${u} updated`}),l())},n=f.find(i=>i.id===s.practice_id),a=h.find(i=>i.id===s.delivery_region_id);return!(s.project_type||s.description||f.length>0||h.length>0||s.target_margin_percent)&&!s.description?null:e.jsx(R,{className:"bg-muted/30",children:e.jsx(A,{className:"py-3 px-4",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-sm",children:[e.jsx(Xe,{icon:e.jsx(os,{className:"h-3.5 w-3.5"}),label:"Type",value:s.project_type,placeholder:"Set type",options:Ua.map(i=>({value:i,label:i})),onSelect:i=>r("project_type",i)}),e.jsx(Xe,{icon:null,label:"Health",value:s.health,placeholder:"Set health",options:Xt,onSelect:i=>r("health",i),renderValue:i=>{const t={excellent:"bg-success/10 text-success border-success/20",good:"bg-primary/10 text-primary border-primary/20",on_track:"bg-primary/10 text-primary border-primary/20",at_risk:"bg-warning/10 text-warning border-warning/20",critical:"bg-destructive/10 text-destructive border-destructive/20"},o=Xt.find(g=>g.value===i)?.label||pe(i);return e.jsx(T,{variant:"outline",className:O("text-xs",t[i||""]),children:o})}}),f.length>0&&e.jsx(Xe,{icon:e.jsx(bt,{className:"h-3.5 w-3.5"}),label:"Practice",value:s.practice_id,placeholder:"Set practice",options:[{value:"__none__",label:"None"},...f.map(i=>({value:i.id,label:i.name}))],onSelect:i=>r("practice_id",i==="__none__"?null:i),renderValue:()=>n?e.jsxs("span",{className:"flex items-center gap-1.5",children:[n.color&&e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:n.color}}),n.name]}):null}),h.length>0&&e.jsx(Xe,{icon:e.jsx(la,{className:"h-3.5 w-3.5"}),label:"Region",value:s.delivery_region_id,placeholder:"Set region",options:[{value:"__none__",label:"None"},...h.filter(i=>i.is_active).map(i=>({value:i.id,label:`${i.name}
48 (${i.code})`}))],onSelect:i=>r("delivery_region_id",i==="__none__"?null:i),renderValue:()=>a?e.jsxs("span",{children:[a.name," (",a.code,")"]}):null}),e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[e.jsx(ns,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Margin:"}),e.jsx(ia,{value:s.target_margin_percent?.toString()||"",placeholder:"Set target %",type:"number",suffix:"%",onSave:async i=>{await r("target_margin_percent",i?parseFloat(i):null)},className:"text-xs"})]}),s.description&&e.jsx(Ka,{description:s.description})]})})})}function Xe({icon:s,label:l,value:p,placeholder:h,options:f,onSelect:u,renderValue:r}){return e.jsxs("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[s,e.jsxs("span",{className:"text-xs font-medium",children:[l,":"]}),e.jsxs(ht,{children:[e.jsx(pt,{asChild:!0,children:e.jsxs("button",{className:"group flex items-center gap-1 hover:text-foreground transition-colors",children:[p&&r?r(p):p?e.jsx("span",{className:"text-xs text-foreground",children:f.find(n=>n.value===p)?.label||pe(p)}):e.jsx("span",{className:"text-xs italic text-muted-foreground/70",children:h}),e.jsx(Nt,{className:"h-2.5 w-2.5 opacity-0 group-hover:opacity-100 transition-opacity"})]})}),e.jsx(gt,{children:f.map(n=>e.jsx(ae,{onClick:()=>u(n.value),className:O(p===n.value&&"bg-accent"),children:n.label},n.value))})]})]})}function Ka({description:s}){const[l,p]=c.useState(!0);return e.jsxs("div",{className:"w-full mt-1",children:[e.jsxs("button",{onClick:()=>p(!l),className:"flex items-center gap-1.5 text-muted-foreground hover:text-foreground transition-colors mb-1",children:[e.jsx(Me,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"text-xs font-medium",children:"Description"}),l?e.jsx(es,{className:"h-3 w-3"}):e.jsx(vt,{className:"h-3 w-3"})]}),l&&e.jsx("div",{className:"pl-5 prose prose-xs dark:prose-invert max-w-none text-xs text-muted-foreground [&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0.5 [&_h1]:text-sm [&_h2]:text-sm [&_h3]:text-xs [&_strong]:text-foreground",children:e.jsx(ds,{remarkPlugins:[ca],children:s})})]})}const Jt={task_completed:{icon:ye,color:"text-success",bgColor:"bg-success/10"},task_updated:{icon:_e,color:"text-primary",bgColor:"bg-primary/10"},task_created:{icon:_e,color:"text-primary",bgColor:"bg-primary/10"},deliverable_created:{icon:Me,color:"text-accent-foreground",bgColor:"bg-accent/30"},deliverable_updated:{icon:Me,color:"text-accent-foreground",bgColor:"bg-accent/30"},deliverable_approved:{icon:ye,color:"text-success",bgColor:"bg-success/10"},deliverable_submitted:{icon:us,color:"text-warning",bgColor:"bg-warning/10"},time_logged:{icon:we,color:"text-muted-foreground",bgColor:"bg-muted"},approval_action:{icon:xa,color:"text-primary",bgColor:"bg-primary/10"}};function Ga(s){const l=`${s.type}_${s.action}`;return Jt[l]||Jt[`${s.type}_updated`]||{icon:_e,color:"text-muted-foreground",bgColor:"bg-muted"}}function Qa(s){switch(s.type){case"task":return s.action==="completed"?"completed task":s.action==="created"?"created task":s.metadata?.status?`changed task status to ${s.metadata.status}`:s.metadata?.assigned_to?"reassigned task":s.metadata?.priority?`set task priority to ${s.metadata.priority}`:"updated task";case"deliverable":return s.action==="created"?"added deliverable":s.action==="approved"?"approved deliverable":s.action==="submitted"?"submitted deliverable for review":"updated deliverable";case"time_entry":return`logged ${s.metadata?.hours||""}h on`;case"approval":return s.action;default:return s.action}}function Ya(s){const l=new Date(s);return ha(l)?"Today":Ea(l)?"Yesterday":Pe(l,"MMM d, yyyy")}function Xa({projectId:s,embedded:l=!1}){const{data:p,isLoading:h}=Ne({queryKey:["project-activity-feed",s],queryFn:async()=>{const r=[];await N.from("task_activity_log").select(` 49 id, action, old_value, new_value, created_at, 50 user:profiles!task_activity_log_user_id_fkey(full_name, avatar_url), 51 task:tasks!task_activity_log_task_id_fkey(title, status) 52 `).eq("tenant_id",(await N.from("tasks").select("tenant_id").eq("project_id",s).limit(1).single()).data?.tenant_id||"").in("task_id",(await N.from("tasks").select("id").eq("project_id",s)).data?.map(d=>d.id)||[]).order("created_at",{ascending:!1}).limit(30);const{data:n}=await N.from("tasks").select("id, title, tenant_id").eq("project_id",s),a=n?.map(d=>d.id)||[],x=n?.[0]?.tenant_id;if(a.length>0&&x){const{data:d}=await N.from("task_activity_log").select(` 53 id, action, old_value, new_value, created_at, 54 user:profiles!task_activity_log_user_id_fkey(full_name, avatar_url), 55 task_id 56 `).in("task_id",a).order("created_at",{ascending:!1}).limit(30),m=Object.fromEntries((n||[]).map(w=>[w.id,w.title]));
56(d||[]).forEach(w=>{const E=w.new_value,L=E?.status==="done";r.push({id:`task-${w.id}`,type:"task",action:L?"completed":"updated",title:m[w.task_id]||"Task",timestamp:w.created_at,actor:w.user,metadata:E||void 0})})}const{data:i}=await N.from("deliverables").select("id, title, status, created_at, updated_at, author_id, review_status").eq("project_id",s).order("updated_at",{ascending:!1}).limit(20),t=new Set;(i||[]).forEach(d=>{d.author_id&&t.add(d.author_id)});const{data:o}=t.size>0?await N.from("profiles").select("id, full_name, avatar_url").in("id",Array.from(t)):{data:[]},g=Object.fromEntries((o||[]).map(d=>[d.id,d]));(i||[]).forEach(d=>{const m=d.created_at===d.updated_at,w=d.review_status==="approved"?"approved":d.review_status==="pending"?"submitted":m?"created":"updated";r.push({id:`del-${d.id}`,type:"deliverable",action:w,title:d.title,timestamp:d.updated_at,actor:d.author_id&&g[d.author_id]||void 0,metadata:{status:d.status}})});const{data:v}=await N.from("time_entries").select(` 57 id, hours, actual_minutes, description, created_at, is_billable, 58 user:profiles!time_entries_user_id_fkey(full_name, avatar_url), 59 task:tasks!time_entries_task_id_fkey(title) 60 `).eq("project_id",s).order("created_at",{ascending:!1}).limit(20);(v||[]).forEach(d=>{const m=d.hours||(d.actual_minutes?d.actual_minutes/60:0);r.push({id:`time-${d.id}`,type:"time_entry",action:"logged",title:d.task?.title||d.description||"Time entry",timestamp:d.created_at,actor:d.user,metadata:{hours:Math.round(m*10)/10,billable:d.is_billable}})});const{data:b}=await N.from("deliverable_approval_audit").select(` 61 id, action, notes, created_at, 62 actor:profiles!deliverable_approval_audit_actor_id_fkey(full_name, avatar_url), 63 deliverable:deliverables!deliverable_approval_audit_deliverable_id_fkey(title, project_id) 64 `).order("created_at",{ascending:!1}).limit(20);return(b||[]).forEach(d=>{d.deliverable?.project_id===s&&r.push({id:`approval-${d.id}`,type:"approval",action:d.action.replace(/_/g," "),title:d.deliverable?.title||"Deliverable",timestamp:d.created_at,actor:d.actor,description:d.notes||void 0})}),r.sort((d,m)=>new Date(m.timestamp).getTime()-new Date(d.timestamp).getTime()),r.slice(0,50)},staleTime:3e4});if(h){const r=e.jsx("div",{className:"space-y-4",children:[1,2,3,4].map(n=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ie,{className:"h-8 w-8 rounded-full shrink-0"}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx(Ie,{className:"h-4 w-3/4"}),e.jsx(Ie,{className:"h-3 w-1/3"})]})]},n))});return l?r:e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(_e,{className:"h-5 w-5"}),"Recent Activity"]})}),e.jsx(A,{children:r})]})}if(!p||p.length===0){const r=e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_e,{className:"h-8 w-8 mx-auto mb-2 opacity-30"}),e.jsx("p",{className:"text-sm",children:"No activity recorded yet"}),e.jsx("p",{className:"text-xs mt-1",children:"Activity will appear as tasks are updated, time is logged, and deliverables change."})]});return l?r:e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(_e,{className:"h-5 w-5"}),"Recent Activity"]})}),e.jsx(A,{children:r})]})}const f={};p.forEach(r=>{const n=Ya(r.timestamp);f[n]||(f[n]=[]),f[n].push(r)});const u=e.jsx(ms,{className:l?"max-h-[180px] pr-3":"h-[400px] pr-3",children:e.jsx("div",{className:"space-y-6",children:Object.entries(f).map(([r,n])=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:r}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx("div",{className:"space-y-1",children:n.map((a,x)=>{const i=Ga(a),t=i.icon,o=Qa(a);return e.jsxs("div",{className:"flex gap-3 py-2 group hover:bg-muted/30 rounded-md px-2 -mx-2 transition-colors",children:[e.jsxs("div",{className:"flex flex-col items-center",children:[e.jsx("div",{className:O("p-1.5 rounded-full shrink-0",i.bgColor),children:e.jsx(t,{className:O("h-3.5 w-3.5",i.color)})}),x<n.length-1&&e.jsx("div",{className:"w-px flex-1 bg-border mt-1"})]}),e.jsx("div",{className:"flex-1 min-w-0 pb-1",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm leading-snug",children:[a.actor?e.jsx("span",{className:"font-medium",children:a.actor.full_name}):e.jsx("span",{className:"font-medium text-muted-foreground",children:"System"})," ",e.jsx("span",{className:"text-muted-foreground",children:o})," ",e.jsx("span",{className:"font-medium",children:a.title}),a.metadata?.billable===!1&&a.type==="time_entry"&&e.jsx(T,{variant:"outline",className:"text-caption ml-1 py-0",children:"non-billable"})]}),a.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:a.description})]}),e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap shrink-0",children:Pe(new Date(a.timestamp),"h:mm a")})]})})]},a.id)})})]},r))})});return l?u:e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs(W,{className:"text-lg flex items-center gap-2",children:[e.jsx(_e,{className:"h-5 w-5"}),"Recent Activity"]})}),e.jsx(A,{children:u})]})}function Ja({projectId:s}){const[l,p]=c.useState(null),[h,f]=c.useState(!0);c.useEffect(()=>{u()},[s]);const u=async()=>{f(!0);try{const{data:n}=await N.from("project_rate_cards").select("role_name, standard_rate, project_rate, discount_pct, discount_amount_per_hour, profile_id, org_level_id").eq("project_id",s),{data:a}=await N.from("time_entries").select("hours, actual_minutes, billable_minutes, is_billable, rate_override, user_id, profiles(hourly_rate, org_level_id, profile_financials(hourly_cost))").eq("project_id",s).eq("is_billable",!0),x=a||[],i=n||[];let t=0,o=0,g=0;const v=new Map;for(const m of x){const w=(m.billable_minutes||m.actual_minutes||(m.hours||0)*60)/60,E=m.profiles,L=E?.hourly_rate||150,C=E?.profile_financials,j=(Array.isArray(C)?C[0]?.hourly_cost:C?.hourly_cost)||0,_=i.find(Q=>Q.profile_id===m.user_id||Q.org_level_id===E?.org_level_id),I=_?.project_rate||m.rate_override||L,$=_?.standard_rate||L;if(t+=w*$,o+=w*I,g+=w*j,_){const Q=_.role_name||"Other",D=v.get(Q);D?D.hours+=w:v.set(Q,{hours:w,standard:_.standard_rate,project:_.project_rate,discount:_.discount_pct||0})}}const b=t-o,d=t>0?b/t*100:0;p({standardRevenue:t,billedRevenue:o,discountImpact:b,discountPercent:d,totalCost:g,grossMarginStandard:t-g,grossMarginActual:o-g,marginPercentStandard:t>0?(t-g)/t*100:0,marginPercentActual:o>0?(o-g)/o*100:0,rateCards:Array.from(v.entries()).map(([m,w])=>({role_name:m,standard_rate:w.standard,project_rate:w.project,discount_pct:w.discount,hours:w.hours,revenueImpact:w.hours*(w.standard-w.project)}))})}catch(n){console.error("Error loading P&L discount data:",n)}finally{f(!1)}};if(h)return e.jsxs(R,{children:[e.jsx(U,{children:e.jsx(W,{className:"text-sm",children:"Project P&L"})}),e.jsx(A,{children:e.jsx(Ie,{className:"h-32 w-full"})})]});if(!l||l.discountImpact===0)return null;const r=n=>
64`$${Math.abs(n).toLocaleString(void 0,{maximumFractionDigits:0})}`;return e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs(W,{className:"flex items-center gap-2 text-sm",children:[e.jsx(fe,{className:"h-4 w-4 text-primary"}),"P&L â Discount Impact",l.discountPercent>15&&e.jsxs(T,{variant:"destructive",className:"text-xs ml-auto",children:[e.jsx(ge,{className:"h-3 w-3 mr-1"}),"High Discount"]})]})}),e.jsxs(A,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Revenue (at standard rates)"}),e.jsx("span",{className:"font-medium",children:r(l.standardRevenue)})]}),e.jsxs("div",{className:"flex justify-between text-destructive",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ts,{className:"h-3 w-3"}),"Discount adjustment (",l.discountPercent.toFixed(1),"%)"]}),e.jsxs("span",{className:"font-medium",children:["â",r(l.discountImpact)]})]}),e.jsx(lt,{}),e.jsxs("div",{className:"flex justify-between font-medium",children:[e.jsx("span",{children:"Billed revenue"}),e.jsx("span",{children:r(l.billedRevenue)})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Cost of delivery"}),e.jsxs("span",{children:["(",r(l.totalCost),")"]})]}),e.jsx(lt,{}),e.jsxs("div",{className:"flex justify-between font-semibold",children:[e.jsx("span",{children:"Gross margin (actual)"}),e.jsxs("span",{className:O(l.grossMarginActual<0?"text-destructive":"text-success"),children:[r(l.grossMarginActual)," (",l.marginPercentActual.toFixed(0),"%)"]})]}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:"Gross margin (at standard rates)"}),e.jsxs("span",{children:[r(l.grossMarginStandard)," (",l.marginPercentStandard.toFixed(0),"%)"]})]})]}),l.rateCards.length>0&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Discount by Role"}),e.jsx("div",{className:"space-y-1.5",children:l.rateCards.map(n=>e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsx("span",{children:n.role_name}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"text-muted-foreground",children:["$",n.standard_rate," â $",n.project_rate]}),e.jsxs(T,{variant:n.discount_pct>15?"destructive":"secondary",className:"text-caption px-1.5",children:[n.discount_pct.toFixed(0),"% off"]}),e.jsxs("span",{className:"w-16 text-right text-destructive",children:["â",r(n.revenueImpact)]})]})]},n.role_name))})]})]})]})}
64function Za({budgetUsed:s,budget:l,projectId:p,onUpdate:h}){const[f,u]=c.useState(!1),[r,n]=c.useState(l.toString()),[a,x]=c.useState(!1),i=c.useRef(null),{toast:t}=xe();c.useEffect(()=>{f&&i.current&&(i.current.focus(),i.current.select())},[f]),c.useEffect(()=>{n(l.toString())},[l]);const o=async()=>{const d=parseFloat(r)||0;if(d===l){u(!1);return}x(!0);const{error:m}=await N.from("projects").update({budget:d}).eq("id",p);x(!1),m?t({title:"Error updating budget",variant:"destructive"}):(t({title:"Budget updated"}),u(!1),h())},g=()=>{n(l.toString()),u(!1)},v=d=>`$${(d/1e3).toFixed(0)}K`,b=d=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(d);return e.jsx(R,{children:e.jsx(A,{className:"py-4 px-4",children:e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption font-medium text-muted-foreground",children:[e.jsx(fe,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Budget Used"})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx(Se,{size:"lg",children:v(s)}),f?e.jsxs("div",{className:"flex items-center gap-1 mt-0.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"of $"}),e.jsx(Ce,{ref:i,type:"number",value:r,onChange:d=>n(d.target.value),onKeyDown:d=>{d.key==="Enter"&&o(),d.key==="Escape"&&g()},className:"h-6 w-28 text-xs px-1.5"}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-5 w-5",onMouseDown:d=>{d.preventDefault(),o()},disabled:a,children:e.jsx(ct,{className:"h-3 w-3 text-success"})}),e.jsx(S,{variant:"ghost",size:"icon",className:"h-5 w-5",onMouseDown:d=>{d.preventDefault(),g()},children:e.jsx(Ps,{className:"h-3 w-3 text-destructive"})})]}):e.jsxs("button",{onClick:()=>u(!0),className:"text-xs text-muted-foreground hover:text-foreground transition-colors group flex items-center gap-1",title:`Budget: ${b(l)} â click to edit`,children:["of ",v(l)," budget",e.jsx(Nt,{className:"h-2.5 w-2.5 opacity-0 group-hover:opacity-100 transition-opacity"})]})]})]})})})}function er({projectId:s,tenantId:l,projectName:p}){const[h,f]=c.useState(null),[u,r]=c.useState(!1),[n,a]=c.useState(!1),{toast:x}=xe(),i=async()=>{r(!0);try{const{data:o,error:g}=await N.functions.invoke("generate-weekly-status",{body:{projectId:s,tenantId:l}});if(g)throw g;if(o?.error)throw new Error(o.error);f(o.report)}catch(o){console.error(o),x({title:"Failed to generate report",variant:"destructive"})}finally{r(!1)}},t=async()=>{h&&(await navigator.clipboard.writeText(h),a(!0),setTimeout(()=>a(!1),2e3))};return e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"flex items-center gap-2 text-sm",children:[e.jsx(Me,{className:"h-4 w-4 text-primary"}),"AI Weekly Status Report"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[h&&e.jsx(S,{variant:"ghost",size:"sm",onClick:t,children:n?e.jsx(ct,{className:"h-4 w-4"}):e.jsx(pa,{className:"h-4 w-4"})}),e.jsx(S,{size:"sm",onClick:i,disabled:u,children:u?e.jsxs(e.Fragment,{children:[e.jsx(Te,{className:"h-4 w-4 mr-1 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"h-4 w-4 mr-1"})," Generate Report"]})})]})]})}),h&&e.jsx(A,{children:e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert",children:e.jsx(ds,{children:h})})})]})}function tr({projectId:s,tasks:l,workstreams:p=[]}){const[h,f]=c.useState(new Map),[u,r]=c.useState(!0);c.useEffect(()=>{n()},[s]);const n=async()=>{const{data:t,error:o}=await N.from("time_entries").select("task_id, hours").eq("project_id",s).not("task_id","is",null).limit(5e3);if(!o&&t){const g=new Map;for(const v of t)v.task_id&&g.set(v.task_id,(g.get(v.task_id)||0)+(v.hours||0));f(g)}r(!1)},a=c.useMemo(()=>{const t=new Map,o={id:"unassigned",name:"Unassigned",totalHours:0,estimatedHours:0,tasks:[]};for(const v of p)t.set(v.id,{id:v.id,name:v.name,totalHours:0,estimatedHours:0,tasks:[]});for(const v of l){const b=h.get(v.id)||0;if(b===0)continue;const d={title:v.title,hours:b,estimated:v.estimated_hours||null};if(v.workstream_id&&t.has(v.workstream_id)){const m=t.get(v.workstream_id);m.totalHours+=b,m.estimatedHours+=v.estimated_hours||0,m.tasks.push(d)}else o.totalHours+=b,o.estimatedHours+=v.estimated_hours||0,o.tasks.push(d)}const g=[...t.values()].filter(v=>v.totalHours>0);return o.totalHours>0&&g.push(o),g.sort((v,b)=>b.totalHours-v.totalHours)},[l,h,p]);if(u)return e.jsxs(R,{children:[e.jsx(U,{className:"pb-2",children:e.jsx(W,{className:"text-base font-semibold",children:"Time Traceability"})}),e.jsx(A,{className:"space-y-3",children:[1,2,3].map(t=>e.jsx(Ie,{className:"h-10 w-full"},t))})]});if(a.length===0)return null;const x=a.reduce((t,o)=>t+o.totalHours,0),i=a.reduce((t,o)=>t+o.estimatedHours,0);return e.jsxs(R,{children:[e.jsx(U,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(W,{className:"text-base font-semibold flex items-center gap-2",children:[e.jsx(we,{className:"h-4 w-4"}),"Time Traceability"]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[x.toFixed(1),"h logged",i>0&&e.jsxs("span",{children:[" / ",i.toFixed(0),"h est."]})]})]})}),e.jsx(A,{className:"space-y-3",children:a.map(t=>{const o=t.estimatedHours>0?t.totalHours/t.estimatedHours*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:t.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-mono text-xs",children:[t.totalHours.toFixed(1),"h"]}),t.estimatedHours>0&&e.jsxs(T,{variant:o>100?"destructive":o>80?"secondary":"outline",className:"text-caption",children:[o.toFixed(0),"%"]})]})]}),t.estimatedHours>0&&e.jsx(je,{value:Math.min(o,100),className:"h-1.5"}),e.jsxs("div",{className:"pl-4 space-y-0.5",children:[t.tasks.slice(0,5).map((g,v)=>e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1 truncate max-w-[70%]",children:[e.jsx(ga,{className:"h-3 w-3"}),g.title]}),e.jsxs("span",{className:"font-mono",children:[g.hours.toFixed(1),"h",g.estimated&&e.jsxs("span",{className:"opacity-60",children:["/",g.estimated,"h"]})]})]},v)),t.tasks.length>5&&e.jsxs("p",{className:"text-caption text-muted-foreground pl-4",children:["+",t.tasks.length-5," more tasks"]})]})]},t.id)})})]})}function sr({projectId:s,currentData:l}){const{toast:p}=xe(),[h,f]=c.useState([]),[u,r]=c.useState(!1);c.useEffect(()=>{n()},[s]);const n=async()=>{const{data:b}=await N.from("project_baselines").select("*").eq("project_id",s).order("taken_at",{ascending:!1}).limit(5);f(b||[])},a=async()=>{r(!0);try{const{error:b}=await N.from("project_baselines").insert({project_id:s,baseline_data:l});if(b)throw b;p({title:"Baseline captured",description:"Current project state has been saved as a baseline snapshot"}),n()}catch(b){p({title:"Error",description:b.message,variant:"destructive"})}finally{r(!1)}},x=h[0],i=(b,d)=>{if(d===0)return{pct:0,direction:"neutral"};
64const m=(b-d)/d*100;return{pct:Math.abs(m),direction:m>2?"up":m<-2?"down":"neutral"}},t=x?i(l.budget,x.baseline_data.budget):null,o=x?i(l.taskCount,x.baseline_data.taskCount):null,g=x?i(l.totalHours,x.baseline_data.totalHours):null,v=({direction:b,pct:d,label:m})=>e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[b==="up"&&e.jsx(ja,{className:"h-3 w-3 text-warning"}),b==="down"&&e.jsx(fa,{className:"h-3 w-3 text-success"}),b==="neutral"&&e.jsx(va,{className:"h-3 w-3 text-muted-foreground"}),e.jsxs("span",{className:O(b==="up"?"text-warning":b==="down"?"text-success":"text-muted-foreground"),children:[d.toFixed(0),"% ",m]})]});return e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(W,{className:"text-base",children:"Project Baseline"}),e.jsx(be,{children:x?`Last baseline: ${new Date(x.taken_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}`:"No baseline captured yet"})]}),e.jsxs(S,{size:"sm",variant:"outline",onClick:a,disabled:u,children:[e.jsx(Es,{className:"h-4 w-4 mr-1.5"}),u?"Saving...":"Take Snapshot"]})]})}),x&&e.jsxs(A,{children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(fe,{className:"h-3 w-3"})," Budget"]}),e.jsxs("p",{className:"text-sm font-medium",children:["$",l.budget.toLocaleString()]}),t&&e.jsx(v,{...t,label:"vs baseline"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(xs,{className:"h-3 w-3"})," Tasks"]}),e.jsx("p",{className:"text-sm font-medium",children:l.taskCount}),o&&e.jsx(v,{...o,label:"scope change"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(we,{className:"h-3 w-3"})," Hours"]}),e.jsxs("p",{className:"text-sm font-medium",children:[l.totalHours.toFixed(0),"h"]}),g&&e.jsx(v,{...g,label:"vs plan"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(yt,{className:"h-3 w-3"})," Due"]}),e.jsx("p",{className:"text-sm font-medium",children:l.endDate?new Date(l.endDate).toLocaleDateString("en-US",{month:"short",day:"numeric"}):"â"}),x.baseline_data.endDate&&l.endDate&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Baseline: ",new Date(x.baseline_data.endDate).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})]})]}),e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Current Progress"}),e.jsxs("span",{className:"font-medium",children:[l.completion,"%"]})]}),e.jsx(je,{value:l.completion,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Baseline at Snapshot"}),e.jsxs("span",{children:[x.baseline_data.completion,"%"]})]}),e.jsx(je,{value:x.baseline_data.completion,className:"h-1.5 opacity-50"})]}),h.length>1&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsxs(T,{variant:"secondary",className:"text-xs",children:[h.length," snapshots"]}),e.jsxs("span",{children:["First: ",new Date(h[h.length-1].taken_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})]})]})]})]})}function ar({budget:s,actualCost:l,completion:p,totalEstimatedHours:h,actualHours:f}){const u=c.useMemo(()=>{const a=Math.max(p,1),x=s*(a/100),i=l>0?x/l:1,t=h>0?Math.min(f/h*100,100):a,o=s*(t/100),g=o>0?x/o:1,v=i>0?s/i:s,b=Math.max(v-l,0),d=s-v,m=s-l,w=m>0?(s-x)/m:0,E=h>0&&f>0&&a>0?f/(a/100):h,L=Math.max(E-f,0);return{cpi:i,spi:g,eac:v,etc:b,vac:d,tcpi:w,earnedValue:x,hoursEAC:E,hoursETC:L}},[s,l,p,h,f]),r=a=>a>=.95&&a<=1.05?"text-success":a>=.8?"text-warning":"text-destructive",n=a=>a>=.95&&a<=1.05?"bg-success/10":a>=.8?"bg-warning/10":"bg-destructive/10";return e.jsxs(R,{children:[e.jsx(U,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(W,{className:"text-base flex items-center gap-2",children:[e.jsx(De,{className:"h-4 w-4"}),"EAC / ETC Forecast"]}),e.jsx(be,{children:"Earned value analysis & project cost forecasting"})]}),e.jsx(T,{variant:"outline",className:O("text-xs",u.vac>=0?"border-success/30 text-success":"border-destructive/30 text-destructive"),children:u.vac>=0?"Under Budget":"Over Budget"})]})}),e.jsxs(A,{children:[e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:O("rounded-lg p-3",n(u.cpi)),children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground mb-1",children:[e.jsx(fe,{className:"h-3 w-3"})," CPI"]}),e.jsx("p",{className:O("text-lg font-bold",r(u.cpi)),children:u.cpi.toFixed(2)}),e.jsx("p",{className:"text-caption text-muted-foreground",children:u.cpi>=1?"Cost efficient":"Over budget pace"})]}),e.jsxs("div",{className:O("rounded-lg p-3",n(u.spi)),children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground mb-1",children:[e.jsx(we,{className:"h-3 w-3"})," SPI"]}),e.jsx("p",{className:O("text-lg font-bold",r(u.spi)),children:u.spi.toFixed(2)}),e.jsx("p",{className:"text-caption text-muted-foreground",children:u.spi>=1?"Ahead of schedule":"Behind schedule"})]}),e.jsxs("div",{className:"rounded-lg p-3 bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground mb-1",children:[e.jsx(De,{className:"h-3 w-3"})," Est. at Completion"]}),e.jsxs("p",{className:"text-lg font-bold",children:["$",u.eac.toLocaleStr
64ing(void 0,{maximumFractionDigits:0})]}),e.jsxs("p",{className:"text-caption text-muted-foreground",children:["Budget: $",s.toLocaleString()]})]}),e.jsxs("div",{className:"rounded-lg p-3 bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground mb-1",children:[e.jsx(fe,{className:"h-3 w-3"})," Est. to Complete"]}),e.jsxs("p",{className:"text-lg font-bold",children:["$",u.etc.toLocaleString(void 0,{maximumFractionDigits:0})]}),e.jsx("p",{className:"text-caption text-muted-foreground",children:"Remaining cost forecast"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-3",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"VAC"}),e.jsxs("p",{className:O("text-sm font-bold",u.vac>=0?"text-success":"text-destructive"),children:[u.vac>=0?"+":"","$",u.vac.toLocaleString(void 0,{maximumFractionDigits:0})]})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"TCPI"}),e.jsx("p",{className:O("text-sm font-bold",r(u.tcpi)),children:u.tcpi.toFixed(2)})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hours ETC"}),e.jsxs("p",{className:"text-sm font-bold",children:[u.hoursETC.toFixed(0),"h"]})]})]}),u.cpi<.85&&e.jsxs("div",{className:"mt-3 flex items-center gap-2 p-2 rounded-lg bg-destructive/10 text-sm",children:[e.jsx(ge,{className:"h-4 w-4 text-destructive shrink-0"}),e.jsxs("span",{className:"text-destructive",children:["CPI is critically low (",u.cpi.toFixed(2),"). Project is trending ",((1-u.cpi)*100).toFixed(0),"% over budget."]})]})]})]})}const rr=c.lazy(()=>B(()=>import("./ProjectManagementHub-VoDKLZdn.js"),__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,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129])).then(s=>({default:s.ProjectManagementHub}))),nr=c.lazy(()=>B(()=>import("./ProgramDashboard-Cy4-nDgy.js"),__vite__mapDeps([130,2,3,4,6,78,1,5,7,8,9,10,124,22,109,71,31,112,53,25,24,27,23,96,79,70,131,51,29,132,133,54,40,11,12,13,14,15,134,52,48,135,89,108,87,90,55,111,30,129,67,114])).then(s=>({default:s.ProgramDashboard}))),ir=c.lazy(()=>B(()=>import("./ProjectDeliverablesTab-Bj-k_2Cd.js"),__vite__mapDeps([136,2,3,4,6,1,5,7,8,9,18,19,41,137,51,71,138,139,78,13,14,15,11,12,22,140,115,114,141,129,111,87,31,142,143,144,90,48,145,29,93])).then(s=>({default:s.ProjectDeliverablesTab}))),lr=c.lazy(()=>B(()=>import("./ProjectTeamAssignment-vy5Ilv3o.js"),__vite__mapDeps([146,2,3,4,78,1,5,6,7,8,9,54,40,119,71,69,68,52,147,148,23,24,50,28,111,98,29,149,150,51,90,48])).then(s=>({default:s.ProjectTeamAssignment}))),cr=c.lazy(()=>B(()=>import("./DecisionLog-DR7W_BU8.js"),__vite__mapDeps([133,2,3,4,96,1,5,6,7,8,78,9,54,40,11,12,13,14,15,134,52,48,51,29,135,71,89,108,53,87,90])).then(s=>({default:s.DecisionLog}))),or=c.lazy(()=>B(()=>import("./ProjectFileBrowser-Dy68yWZS.js"),__vite__mapDeps([151,2,3,4,78,1,5,6,7,8,9,13,14,15,79,28,152,10,153,154,155,156,157,158,159,160,51,82,161,71,162,111,114,67,31,127,163,44,164,89,84,105,53,85,165,166,167,168])).then(s=>({default:s.ProjectFileBrowser}))),dr=c.lazy(()=>B(()=>import("./MilestoneApproval-CrZ_4EPF.js"),__vite__mapDeps([169,2,3,4,6,78,1,5,7,8,9,54,40,10,11,12,170,134,67,111,31,32,171,71,14,52,90,23,24])).then(s=>({default:s.MilestoneApproval}))),mr=c.lazy(()=>B(()=>import("./TranscriptAnalysisPanel-C7g24hOI.js"),__vite__mapDeps([172,2,3,4,78,1,5,6,7,8,9,28,173,18,122,104,52,138,58,51,97,127,114,48,162,87,174,68,111,32,84,31,132,23,24,29,105,128,71,53])).then(s=>({default:s.TranscriptAnalysisPanel}))),ur=c.lazy(()=>B(()=>import("./EngagementValueThread-DgBD8tae.js"),__vite__mapDeps([175,2,3,4,6,78,1,5,7,8,9,112])).then(s=>({default:s.EngagementValueThread}))),xr=c.lazy(()=>B(()=>
64import("./SOWUploadExtractor-Bwap4d86.js"),__vite__mapDeps([176,2,3,4,1,5,6,7,8,78,9,18,156,157,158,82,51,31])).then(s=>({default:s.SOWUploadExtractor}))),hr=c.lazy(()=>B(()=>import("./HistoricalFinancialsPanel-ATO1ETnB.js"),__vite__mapDeps([177,2,3,4,96,1,5,6,7,8,78,9,103,124,10,28,166,82,84,90,67,29,123,108])).then(s=>({default:s.HistoricalFinancialsPanel}))),pr=c.lazy(()=>B(()=>import("./ClientPortalConfig-B63KYLfx.js"),__vite__mapDeps([178,2,3,4,78,1,5,6,7,8,79,9,18,20,179,180,111,181,53])).then(s=>({default:s.ClientPortalConfig}))),gr=c.lazy(()=>B(()=>import("./StatusReportComposer-1IrGYrTa.js"),__vite__mapDeps([182,2,3,4,6,1,5,7,8,78,9,51,53,29,23,24])).then(s=>({default:s.StatusReportComposer}))),jr=c.lazy(()=>B(()=>import("./PhasesMilestonesDialog-StKHFkEy.js"),__vite__mapDeps([183,2,3,4,1,5,6,7,8,79,129,32])).then(s=>({default:s.PhasesMilestonesDialog}))),fr=c.lazy(()=>B(()=>import("./TranscriptUploadDialog-CCZ8_aPY.js"),__vite__mapDeps([184,2,3,4,1,5,6,7,8,185,155,154,82])).then(s=>({default:s.TranscriptUploadDialog}))),vr=c.lazy(()=>B(()=>import("./GranolaMeetingBrowser-BDUWnfl4.js"),__vite__mapDeps([186,2,3,4,19,1,5,6,7,8,9,28,47,127,31,187,71,111,48,135,23,24])).then(s=>({default:s.GranolaMeetingBrowser}))),_r=c.lazy(()=>B(()=>import("./ProjectCompletionWizard-C4bVL-h2.js"),__vite__mapDeps([188,2,3,4,1,5,6,7,8,115,78,9,50,10,189,48,90,71,67,190,98,31,191,134,51,30,14,68,13,15,192,54,40,193,194,173,195,43,47,196,103,197,198,199,28,18,127,200,201,111,141,202,171,96,52,69,105,23,24,203,204,131,205,70,206,135,207,114,11,12,124,22,162,29,49,110,208,129,117,209,20,72,74,35,60,25,82,87,94,118,132,210,211,212,16,17,19,21,122,89,138,164,32,213,108])).then(s=>({default:s.ProjectCompletionWizard}))),br=c.lazy(()=>B(()=>import("./ProjectTimelinePanel-7gldqYYs.js"),__vite__mapDeps([214,2,3,4,19,1,5,6,7,8,28,9,52,71,112,32,114,111,23,24])).then(s=>({default:s.ProjectTimelinePanel}))),yr=c.lazy(()=>B(()=>import("./SOWUploadToProjectDialog-CncU6ePC.js"),__vite__mapDeps([215,1,2,3,4,5,6,7,8,78,9,50,103,82,14,30,201,141,67,129,98,51])).then(s=>({default:s.SOWUploadToProjectDialog}
64))),Nr=c.lazy(()=>B(()=>import("./ChangeOrderDialog-mssk1FNb.js"),__vite__mapDeps([216,2,3,4,1,5,6,7,8,9,78,28,204,67,52,48,105,31])).then(s=>({default:s.ChangeOrderDialog}))),wr=c.lazy(()=>B(()=>import("./ProjectTemplateDialog-DBuNYn72.js"),__vite__mapDeps([217,2,3,4,1,5,6,7,8,9,78,28,129,53])).then(s=>({default:s.ProjectTemplateDialog})));function ce(){return e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Te,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}const Je={active:{variant:"active",label:"Active"},completed:{variant:"completed",label:"Completed"},on_hold:{variant:"on_hold",label:"On Hold"},cancelled:{variant:"cancelled",label:"Cancelled"},not_started:{variant:"draft",label:"Not Started"},in_progress:{variant:"in_progress",label:"In Progress"}},Ze={excellent:{variant:"excellent",label:"Excellent",icon:ye},good:{variant:"good",label:"On Track",icon:ye},on_track:{variant:"good",label:"On Track",icon:ye},at_risk:{variant:"at_risk",label:"At Risk",icon:Wt},critical:{variant:"critical",label:"Critical",icon:Wt}},kr=["management","program","deliverables","team","decisions","files","approvals","transcripts","billing","portal"];function Cr(){const{id:s}=Fs(),l=Ls(),[p,h]=$s(),{toast:f}=xe(),{isAdmin:u}=_a(),r=p.get("tab"),[n,a]=c.useState(!1),x=kr.includes(r)?r:n?"program":"management",i=c.useCallback(y=>{h(F=>{const Ae=new URLSearchParams(F);return y==="management"?Ae.delete("tab"):Ae.set("tab",y),Ae},{replace:!0})},[h]),[t,o]=c.useState(null),{data:g}=kt(s),[v,b]=c.useState(!0),[d,m]=c.useState(!1),[w,E]=c.useState(!1),[L,C]=c.useState(null),[j,_]=c.useState(null),[I,$]=c.useState(0),[Q,D]=c.useState(0),[k,M]=c.useState([]),[G,q]=c.useState(!1),[J,Z]=c.useState(!1),[Y,z]=c.useState(!1),[oe,de]=c.useState(0),[He,P]=c.useState(null),[ee,ve]=c.useState(null),[he,Ee]=c.useState(!1),[Ve,Ct]=c.useState(!1),[St,Tt]=c.useState(!1),[Mt,Dt]=c.useState(!1),[Pt,ot]=c.useState(!1),[Et,Rt]=c.useState(!1),[ps,gs]=c.useState("save"),[Re,js]=c.useState(!1),[fs,vs]=c.useState([]),{setOpen:dt,open:Mr}=ba(),Ue=c.useCallback(()=>{js(y=>{const F=!y;return F?(dt(!1),Ee(!1)):dt(!0),F})},[dt]);c.useEffect(()=>{const y=F=>{F.key==="Escape"&&Re&&Ue(),F.key==="f"&&(F.metaKey||F.ctrlKey)&&F.shiftKey&&(F.preventDefault(),Ue())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[Re,Ue]),c.useEffect(()=>{s&&(o(null),b(!0),a(!1),M([]),$(0),D(0),Ee(!1),K())},[s]);const K=async()=>{try{const{data:y,error:F}=await N.from("projects").select("*, clients (name)").eq("id",s).single();if(F)throw F;const{data:Ae}=await N.from("proposals").select("id, title, project_lead_id").eq("linked_project_id",s).maybeSingle(),{data:bs}=await N.from("workstreams").select("*").eq("project_id",s).order("sort_order"),{data:Ft}=await N.from("tasks").select(` 65 *, 66 assignee:profiles!tasks_assigned_to_fkey(full_name, avatar_url), 67 subtasks(id, title, status, estimated_hours, sort_order, assigned_to) 68 `).eq("project_id",s).order("created_at"),{data:ys}=await N.from("deliverables").select("*").eq("project_id",s).order("due_date"),{count:Ns}=await N.from("project_team_members").select("*",{count:"exact",head:!0}).eq("project_id",s),{count:ws}=await N.from("decision_points").select("*",{count:"exact",head:!0}).eq("project_id",s);$(Ns||0),D(ws||0);const ks=(bs||[]).map(me=>({...me,tasks:(Ft||[]).filter(Fe=>Fe.workstream_id===me.id)})),Cs=(Ft||[]).filter(me=>!me.workstream_id),Lt={...y,workstreams:ks,deliverables:ys||[],tasks:Cs,source_proposal:Ae};if(o(Lt),Lt.is_program){a(!0);const{data:me}=await N.from("projects").select("id").eq("parent_project_id",s);vs((me||[]).map(Fe=>Fe.id))}const{data:Ke}=await N.from("phases").select("id, name, description, status, start_date, end_date, sort_order").eq("project_id",s).order("sort_order");if(Ke&&Ke.length>0){const me=Ke.map(te=>te.id),{data:Fe}=await N.from("milestones").select("*").in("phase_id",me).order("sort_order"),{data:mt}=await N.from("tasks").select(` 69 id, title, description, status, priority, start_date, due_date, 70 estimated_hours, actual_hours, risk_flag, phase_id, milestone_id, assigned_to, 71 tenant_id, project_id, workstream_id, 72 assignee:profiles!tasks_assigned_to_fkey(full_name, avatar_url), 73 subtasks(id, title, status, estimated_hours, sort_order, assigned_to) 74 `).in("phase_id",me).order("created_at"),ut=(mt||[]).map(te=>te.id),{data:Ss}=await N.from("task_dependencies").select("predecessor_id, successor_id, dependency_type").or(ut.length>0?`predecessor_id.in.(${ut.join(",")}),successor_id.in.(${ut.join(",")})`:"id.is.null"),Ge=new Map;
74(Ss||[]).forEach(te=>{const X=Ge.get(te.successor_id)||[];X.push({predecessor_id:te.predecessor_id,dependency_type:te.dependency_type||"finish_to_start"}),Ge.set(te.successor_id,X)});const Ts=Ke.map(te=>({...te,milestones:(Fe||[]).filter(X=>X.phase_id===te.id).map(X=>({...X,tasks:(mt||[]).filter(Le=>Le.milestone_id===X.id).map(Le=>({...Le,assignee:Le.assignee,dependencies:Ge.get(Le.id)||[]}))})),tasks:(mt||[]).filter(X=>X.phase_id===te.id&&!X.milestone_id).map(X=>({...X,assignee:X.assignee,dependencies:Ge.get(X.id)||[]}))}));M(Ts)}else M([])}catch(y){console.error("Error loading project:",y),f({title:"Error",description:"Could not load project",variant:"destructive"})}finally{b(!1)}};if(v)return e.jsxs("div",{className:"space-y-4 p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted animate-pulse"}),e.jsxs("div",{className:"space-y-2 flex-1",children:[e.jsx("div",{className:"h-6 w-48 bg-muted animate-pulse rounded"}),e.jsx("div",{className:"h-4 w-32 bg-muted animate-pulse rounded"})]})]}),e.jsx("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4",children:[1,2,3,4].map(y=>e.jsx("div",{className:"h-20 bg-muted animate-pulse rounded-lg"},y))}),e.jsx("div",{className:"h-10 bg-muted animate-pulse rounded-lg"}),e.jsx("div",{className:"h-64 bg-muted animate-pulse rounded-lg"})]});if(!t)return e.jsxs("div",{className:"text-center py-12",children:[e.jsx(zt,{className:"h-12 w-12 text-muted-foreground/30 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Project not found"}),e.jsx(S,{variant:"link",onClick:()=>l("/projects"),children:"Back to Projects"})]});const We=[...t.tasks||[],...t.workstreams?.flatMap(y=>y.tasks||[])||[]],_s=We.filter(y=>y.status==="done").length,At=We.length;return e.jsxs(is.div,{initial:{opacity:0}
74,animate:{opacity:1},className:"flex flex-col -mx-2 sm:-mx-4 md:-mx-6 px-3 sm:px-6 md:px-8 pt-4",children:[e.jsxs(Rs,{value:x,onValueChange:i,className:"flex-1 flex flex-col min-h-0",children:[he&&e.jsxs("div",{className:"shrink-0 space-y-4 pt-2 pb-3",children:[e.jsxs("div",{className:"flex items-start sm:items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-start sm:items-center gap-2 sm:gap-3 min-w-0",children:[e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>l("/projects"),className:"shrink-0 h-8 w-8 mt-0.5 sm:mt-0","aria-label":"Back",children:e.jsx(Ht,{className:"h-4 w-4"})}),e.jsx("div",{className:"min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2 sm:gap-3 flex-wrap",children:[e.jsx(Sr,{value:t.name,onSave:async y=>{const{error:F}=await N.from("projects").update({name:y}).eq("id",t.id);F?f({title:"Error updating name",variant:"destructive"}):(f({title:"Name updated"}),K())}}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[t.status&&e.jsx(T,{variant:Je[t.status]?.variant||"secondary",className:"text-xs",children:Je[t.status]?.label||t.status?.replace(/_/g," ").replace(/\b\w/g,y=>y.toUpperCase())}),t.health&&e.jsx(T,{variant:Ze[t.health]?.variant||"secondary",className:"text-xs",children:Ze[t.health]?.label||t.health?.replace(/_/g," ").replace(/\b\w/g,y=>y.toUpperCase())}),g&&!g.isDefaulted&&e.jsx(T,{variant:"outline",className:"text-xs",children:wt[g.model]})]})]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(ht,{children:[e.jsx(pt,{asChild:!0,children:e.jsx(S,{variant:"outline",size:"icon",className:"h-8 w-8","aria-label":"More options",children:e.jsx(ya,{className:"h-4 w-4"})})}),e.jsxs(gt,{align:"end",children:[e.jsx(ae,{onClick:()=>E(!0),children:"Edit Project"}),e.jsxs(ae,{onClick:()=>Dt(!0),children:[e.jsx(us,{className:"h-4 w-4 mr-2"}),"Upload SOW"]}),e.jsx(ae,{onClick:()=>Tt(!0),children:"View Timeline"}),e.jsx(ae,{onClick:()=>{gs("save"),Rt(!0)},children:"Save as Template"}),e.jsxs(ae,{onClick:()=>{ot(!0)},children:[e.jsx(ss,{className:"h-4 w-4 mr-2"}),"Change Orders"]}),e.jsx(Os,{}),t.status!=="completed"&&e.jsxs(ae,{className:"text-primary",onClick:()=>Ct(!0),children:[e.jsx(Na,{className:"h-4 w-4 mr-2"}),"Complete Project"]}),e.jsx(ae,{className:"text-destructive",onClick:async()=>{if(!confirm("Are you sure you want to archive this project? It will be hidden from the project list."))return;const{error:y}=await N.from("projects").update({is_archived:!0}).eq("id",t.id);y?f({title:"Error archiving project",description:y.message,variant:"destructive"}):(f({title:"Project archived",description:"The project has been archived successfully."}),l("/projects"))},children:"Archive Project"})]})]}),t.status==="completed"&&e.jsx(Va,{projectId:t.id,projectName:t.name,projectStatus:t.status,className:"h-8"})]})]}),e.jsx(Wa,{project:t,onUpdate:K}),e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4",children:[e.jsx(R,{children:e.jsx(A,{className:"py-4 px-4",children:e.jsx(qt,{label:"Complete",icon:e.jsx(ye,{className:"h-3.5 w-3.5"}),value:`${t.completion_percentage||0}%`})})}),e.jsx(R,{children:e.jsx(A,{className:"py-4 px-4",children:e.jsx(qt,{label:"Tasks Done",icon:e.jsx(xs,{className:"h-3.5 w-3.5"}),value:`${_s}/${At}`})})}),e.jsx(Za,{budgetUsed:t.budget_used||0,budget:t.budget||0,projectId:t.id,onUpdate:K}),e.jsx(R,{children:e.jsx(A,{className:"py-4 px-4",children:e.jsxs("div",{className:"space-y-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-caption font-medium text-muted-foreground",children:[e.jsx(yt,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Due Date"})]}),e.jsx("div",{className:"min-w-0",children:e.jsx(Tr,{value:t.end_date,label:"Due Date",onSave:async y=>{const{error:F}=await N.from("projects").update({end_date:y||null}).eq("id",t.id);F?f({title:"Error updating due date",variant:"destructive"}):(f({title:"Due date updated"}),K())}})})]})})})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(R,{className:"flex flex-col",children:e.jsxs(A,{className:"py-4 px-4 flex-1 flex flex-col",children:[e.jsxs("div",{className:"flex justify-between text-sm mb-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Overall Progress"}),e.jsxs("span",{className:"font-medium",children:[t.completion_percentage||0,"%"]})]}),e.jsx(je,{value:t.completion_percentage||0,className:"h-2 mb-4"}),e.jsx(Xa,{projectId:t.id,embedded:!0})]})}),e.jsx(Aa,{projectId:t.id,budget:t.budget||0,projectTargetMargin:t.target_margin_percent,completion:t.completion_percentage||0,startDate:t.start_date}),e.jsx(Ia,{projectId:t.id,budget:t.budget||0,totalCost:t.total_cost||0,totalRevenue:t.budget_used||0,marginPercent:t.margin_percent||0,targetMargin:t.target_margin_percent||35})]}),e.jsx(za,{projectId:t.id}),e.jsx(Ha,{projectId:t.id,tenantId:t.tenant_id}),e.jsx(tr,{projectId:t.id,tasks:We.map(y=>({id:y.id,title:y.title,estimated_hours:y.estimated_hours,workstream_id:y.workstream_id})),workstreams:(t.workstreams||[]).map(y=>({id:y.id,name:y.name}))}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsx(sr,{projectId:t.id,currentData:{budget:t.budget||0,completion:t.completion_percentage||0,taskCount:At,endDate:t.end_date,totalHours:t.budget_hours||0}}),e.jsx(ar,{budget:t.budget||0,actualCost:t.total_cost||t.budget_used||0,completion:t.completion_percentage||0,totalEstimatedHours:t.budget_hours||0,actualHours:t.actual_hours||0})]}),e.jsx($a,{projectId:t.id,budget:t.budget||0,completion:t.completion_percentage||0,targetMargin:t.target_margin_percent??35,onOpenChangeOrders:()=>ot(!0)}),e.jsx(Ba,{projectId:t.id}),e.jsx(Ja,{projectId:t.id}),e.jsx(er,{projectId:t.id,tenantId:t.tenant_id,projectName:t.name}),t.source_proposal&&e.jsx(R,{className:"bg-primary/5 border-primary/20",children:e.jsxs(A,{className:"py-2.5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Me,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Created from proposal"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.source_proposal.title})]})]}),e.jsx(S,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(qs,{to:`/proposals/${t.source_proposal.id}`,children:[e.jsx(Vt,{className:"h-4 w-4 mr-2"}),"View Proposal"]})})]})})]}),e.jsx("div",{className:"sticky top-0 z-[9] bg-background border-b border-border -mx-6 md:-mx-8 px-6 md:px-8",children:e.jsxs("div",{className:"flex items-center",children:[!he&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0 mr-3",children:[e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsx(S,{variant:"ghost",size:"icon",onClick:()=>l("/projects"),className:"h-8 w-8","aria-label":"Back",children:e.jsx(Ht,{className:"h-4 w-4"})})}),e.jsx(ie,{children:"Back to Projects"})]}),e.jsx("span",{className:"text-sm font-semibold truncate max-w-[200px]",children:t.name}),t.status&&e.jsx(T,{variant:Je[t.status]?.variant||"secondary",className:"text-caption px-1.5 py-0",children:Je[t.status]?.label||t.status}),t.health&&e.jsx(T,{variant:Ze[t.health]?.variant||"secondary",className:"text-caption px-1.5 py-0",children:Ze[t.health]?.label||t.health}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[t.completion_percentage||0,"%"]})]}
74),e.jsxs(ms,{className:"flex-1",children:[e.jsxs(As,{className:"inline-flex w-max bg-transparent h-auto p-0 gap-0",children:[e.jsxs(ke,{value:"management",className:"gap-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-4 py-2.5",children:[e.jsx(zt,{className:"h-4 w-4"}),"Project Management"]}),t.is_program&&e.jsxs(ke,{value:"program",className:"gap-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-4 py-2.5",children:[e.jsx(os,{className:"h-4 w-4"}),"Program"]}),e.jsxs(ke,{value:"deliverables",className:"gap-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-4 py-2.5",children:[e.jsx(Me,{className:"h-4 w-4"}),"Deliverables",e.jsx(T,{variant:"secondary",className:"ml-1",children:t.deliverables?.length||0})]}),e.jsxs(ke,{value:"team",className:"gap-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-4 py-2.5",children:[e.jsx(bt,{className:"h-4 w-4"}),"Team",e.jsx(T,{variant:"secondary",className:"ml-1",children:I})]}),e.jsxs(ke,{value:"decisions",className:"gap-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-4 py-2.5",children:[e.jsx(wa,{className:"h-4 w-4"}),"Decisions",e.jsx(T,{variant:"secondary",className:"ml-1",children:Q})]}),e.jsxs(ke,{value:"files",className:"gap-2 rounded-none border-b-2 border-transparent data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:shadow-none px-4 py-2.5",children:[e.jsx(ka,{className:"h-4 w-4"}),"Files"]}),e.jsxs(ht,{children:[e.jsx(pt,{asChild:!0,children:e.jsxs(S,{variant:"ghost",size:"sm",className:"h-9 px-3 gap-1",children:["More",e.jsx(vt,{className:"h-3 w-3"})]})}),e.jsxs(gt,{align:"end",children:[e.jsxs(ae,{onClick:()=>i("approvals"),children:[e.jsx(Ca,{className:"h-4 w-4 mr-2"}),"Approvals"]}),e.jsxs(ae,{onClick:()=>i("transcripts"),children:[e.jsx(Ut,{className:"h-4 w-4 mr-2"}),"Transcripts"]}),e.jsxs(ae,{onClick:()=>i("billing"),children:[e.jsx(fe,{className:"h-4 w-4 mr-2"}),"Billing & SOW"]}),e.jsxs(ae,{onClick:()=>i("portal"),children:[e.jsx(Vt,{className:"h-4 w-4 mr-2"}),"Client Portal"]})]})]})]}),e.jsx(oa,{orientation:"horizontal"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-2",children:[e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsx(S,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>Ee(y=>!y),"aria-label":"Collapse header",children:he?e.jsx(Da,{className:"h-4 w-4"}):e.jsx(Pa,{className:"h-4 w-4"})})}),e.jsx(ie,{children:he?"Collapse header":"Expand header"})]}),e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsx(S,{variant:Re?"secondary":"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:Ue,"aria-label":"Minimize",children:Re?e.jsx(Ma,{className:"h-4 w-4"}):e.jsx(Ta,{className:"h-4 w-4"})})}),e.jsx(ie,{children:Re?"Exit focus mode (Esc)":"Focus mode (ââ§F)"})]}),e.jsxs(re,{children:[e.jsx(ne,{asChild:!0,children:e.jsx(S,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground",onClick:()=>l(`/projects/${t.id}/work`),"aria-label":"Open work mode",children:e.jsx(Sa,{className:"h-4 w-4"})})}),e.jsx(ie,{children:"Work mode â full-screen plan & board"})]})]})]})}),t.is_program&&e.jsx(le,{value:"program",className:"flex-1 flex flex-col min-h-0 mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(nr,{programId:t.id,programName:t.name,tenantId:t.tenant_id})})}),e.jsx(le,{value:"management",className:"flex-1 flex flex-col min-h-0 mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(rr,{projectId:t.id,projectName:t.name,workstreams:t.workstreams||[],budget:t.budget,budgetUsed:t.budget_used,allTasks:We,ganttPhases:k,projectStartDate:t.start_date,projectEndDate:t.end_date,onRefresh:K,onEditTask:y=>{_(y),m(!0)},onAddTask:(y,F)=>{C(y||null),F?.dueDate&&P(F.dueDate),F?.status&&ve(F.status),m(!0)},onShowPhasesMilestones:()=>q(!0)})})}
74),e.jsx(le,{value:"deliverables",className:"space-y-4 mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(ir,{projectId:t.id,deliverables:t.deliverables||[],workstreams:t.workstreams||[],onUpdate:K})})}),e.jsx(le,{value:"team",className:"mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(lr,{projectId:t.id,projectLeadId:t.source_proposal?.project_lead_id,onUpdate:K,isProgram:!!t.is_program})})}),e.jsx(le,{value:"decisions",className:"mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(cr,{projectId:t.id,childProjectIds:t.is_program?fs:void 0})})}),e.jsx(le,{value:"files",className:"mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(or,{projectId:t.id})})}),e.jsx(le,{value:"approvals",className:"mt-0 pt-4",children:e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(dr,{projectId:t.id})})}),e.jsxs(le,{value:"transcripts",className:"space-y-4 mt-0 pt-4",children:[e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(S,{variant:"outline",onClick:()=>z(!0),children:[e.jsx(Ut,{className:"h-4 w-4 mr-2"}),"Import from Granola"]}),e.jsxs(S,{onClick:()=>Z(!0),children:[e.jsx(ls,{className:"h-4 w-4 mr-2"}),"Add Transcript"]})]}),e.jsx(c.Suspense,{fallback:e.jsx(ce,{}),children:e.jsx(mr,{projectId:t.id,isProgram:!!t.is_program,onRefresh:K},`transcripts-${oe}`)})]}),e.jsx(le,{value:"billing",className:"mt-0 pt-4 space-y-6",children:e.jsxs(c.Suspense,{fallback:e.jsx(ce,{}),children:[e.jsx(ur,{projectId:t.id}),e.jsx(xr,{projectId:t.id,tenantId:t.tenant_id}),e.jsx(hr,{projectId:t.id})]})}),e.jsx(le,{value:"portal",className:"mt-0 pt-4 space-y-6",children:e.jsxs(c.Suspense,{fallback:e.jsx(ce,{}),children:[e.jsx(gr,{projectId:t.id}),e.jsx(pr,{projectId:t.id,clientId:t.client_id})]})})]}),e.jsx(Bs,{open:d,onOpenChange:y=>{m(y),y||(_(null),P(null),ve(null))},onSuccess:K,projectId:t.id,workstreamId:L,task:j}),e.jsx(Is,{open:w,onOpenChange:E,project:t,onSuccess:K}),e.jsxs(c.Suspense,{fallback:null,children:[G&&e.jsx(jr,{open:G,onOpenChange:q,projectId:t.id,onSuccess:K}),J&&e.jsx(fr,{open:J,onOpenChange:Z,projectId:t.id,onSuccess:()=>{K(),de(y=>y+1)}}),Y&&e.jsx(vr,{open:Y,onOpenChange:z,projectId:t.id,linkedEntity:"project",linkedId:t.id,linkedName:t.name,onMeetingImported:()=>{K(),de(y=>y+1)}}),Ve&&e.jsx(_r,{open:Ve,onOpenChange:Ct,project:{id:t.id,name:t.name,description:t.description,client_id:t.client_id,project_type:t.project_type,budget:t.budget,budget_used:t.budget_used,completion_percentage:t.completion_percentage,start_date:t.start_date,end_date:t.end_date,clients:t.clients,deliverables:t.deliverables,tasks:t.tasks},onComplete:K}),St&&e.jsx(br,{open:St,onOpenChange:Tt,projectName:t.name,events:[...t.created_at?[{id:"created",type:"created",title:"Project created",date:t.created_at}]:[],...t.start_date?[{id:"started",type:"started",title:"Project kick-off",date:t.start_date}]:[],...t.deliverables?.filter(y=>y.due_date).map(y=>({id:`deliverable-${y.id}`,type:"deliverable",title:y.title,description:y.status==="approved"?"Approved":y.status==="completed"?"Completed":`Due: ${y.due_date}`,date:y.due_date}))||[],...t.end_date?[{id:"end",type:"milestone",title:"Project deadline",date:t.end_date}]:[]].sort((y,F)=>new Date(y.date).getTime()-new Date(F.date).getTime())}),Mt&&e.jsx(yr,{open:Mt,onOpenChange:Dt,projectId:t.id,project:{id:t.id,name:t.name,client_id:t.client_id,tenant_id:t.tenant_id},onComplete:K}),Pt&&e.jsx(Nr,{open:Pt,onOpenChange:ot,projectId:t.id,projectName:t.name,isAdmin:u}),Et&&e.jsx(wr,{open:Et,onOpenChange:Rt,projectId:t.id,projectName:t.name,mode:ps})]})]})}function Sr({value:s,onSave:l}){const[p,h]=c.useState(!1),[f,u]=c.useState(s),r=c.useRef(null);c.useEffect(()=>{u(s)},[s]),c.useEffect(()=>{p&&r.current&&(r.current.focus(),r.current.select())},[p]);const n=async()=>{f.trim()&&f!==s&&await l(f.trim()),h(!1)};return p?e.jsx("input",{ref:r,value:f,onChange:a=>u(a.target.value),onKeyDown:a=>{a.key==="Enter"&&n(),a.key==="Escape"&&(u(s),h(!1))},onBlur:n,className:"text-base sm:text-lg font-semibold tracking-tight bg-transparent border-b-2 border-primary outline-none w-full min-w-[200px]"}):e.jsxs("h1",{onClick:()=>h(!0),className:"text-base sm:text-lg font-semibold tracking-tight truncate cursor-pointer hover:text-primary transition-colors group flex items-center gap-1",children:[s,e.jsx(hs,{className:"h-3 w-3 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground"})]})}function Tr({value:s,label:l,onSave:p}){const[h,f]=c.useState(!1),[u,r]=c.useState(s||""),n=c.useRef(null);c.useEffect(()=>{r(s||"")},[s]),c.useEffect(()=>{h&&n.current&&n.current.focus()},[h]);const a=async()=>{u!==(s||"")&&await p(u),f(!1)};return h?e.jsx("div",{children:e.jsx("input",{ref:n,type:"date",value:u,onChange:x=>r(x.target.value),onKeyDown:x=>{x.key==="Enter"&&a(),x.key==="Escape"&&(r(s||""),f(!1))},onBlur:a,className:"text-sm font-bold bg-transparent border-b-2 border-primary outline-none","aria-label":l})}):e.jsx("button",{onClick:()=>f(!0),className:"text-left group","aria-label":`Edit ${l}`,children:e.jsxs("span",{className:"group-hover:text-primary transition-colors flex items-center gap-1",children:[e.jsx(Se,{size:"lg",children:s?new Date(s).toLocaleDateString("en-US",{month:"short",day:"numeric"}):"â"}),e.jsx(hs,{className:"h-3 w-3 opacity-0 group-hover:opacity-100 transition-opacity text-muted-foreground"})]})})}const ei=Object.freeze(Object.defineProperty({__proto__:null,default:Cr},Symbol.toStringTag,{value:"Module"}));
74export{wt as C,ei as P};
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.