1import{j as e}from"./ui-Bfxz8aEs.js";import{r as F,k as Us}from"./vendor-B1fWbc4m.js";import{M as kt}from"./MetricCard-BWTUZvCC.js";import{d as ua,g as me,i as Ce,T as Je,j as Ae,aU as ke,h as le,a1 as Hs,U as Qe,O as Vs,e as de,o as V,aa as Ve,aK as xs,Q as nt,W as xa,cr as pa,d3 as na,K as ge,B as pe,I as ia,aL as qs,f as Ks,D as _t,u as ga,s as at,q as ra,bq as Ka,cx as zt,r as la,t as oa,v as ca,w as da,aC as fa,ao as ja,L as Se,af as Me,G as ps,al as gs,X as ya,a2 as fs,an as pt,am as dt,ak as Xs,aZ as Zs,aT as Js,p as va,as as Qs,C as en,aD as tn,aE as an,aF as sn,aG as nn,Z as rn,x as Xa,y as Za,z as Ja,E as Qa,F as Qt,b5 as ln,d4 as es,bB as on,at as js,ar as cn,V as ys,P as lt,ag as dn,b9 as mn,bA as hn,aI as vs,ce as Ns,ab as ts,ac as as,ad as ss,b8 as un,bM as Rt,l as xn,m as pn,b6 as gn,n as fn}from"./index-dy_MsEBA.js";import{f as A,g as bs,a as mt,c as yt,D as Fe,b as Ss,u as jn,d as ns}from"./useSavedProjections-LdiwZz0x.js";import{T as Na,a as ba,b as Ue,c as He}from"./tabs-F9h186Z4.js";import{R as Te,T as De,L as Ge,a1 as ma,B as be,C as ws}from"./generateCategoricalChart-DZecInQj.js";import{B as ot}from"./BarChart-Jio-MawF.js";import{C as Le}from"./CartesianGrid-Br1QB36h.js";import{X as Ye,Y as Oe}from"./YAxis-XWNBrjZA.js";import{C as Ps}from"./ComposedChart-DqxOASMV.js";import{A as is}from"./Area-Cc7Zd6wB.js";import{a as Ze,L as Ms}from"./LineChart-BOG5RHpO.js";import{A as yn}from"./AreaChart-BzHdUJ55.js";import{A as vn,a as Nn,b as bn,c as Sn}from"./accordion-Dnsjq8er.js";import{M as wn}from"./minus-Cvq07RB-.js";import{T as Pn}from"./trending-down-CmBOaM0V.js";import{utils as We,writeFile as Mn,read as Cs}from"./xlsx-D_0l8YDs.js";import{T as gt,a as ft,b as ae,c as Ne,d as jt,e as I}from"./table-bKhJjJWF.js";import{F as Gt}from"./file-spreadsheet-DH6xEp_e.js";import{E as ks}from"./jspdf.es.min-D4AOcq1U.js";import{a as ct}from"./jspdf.plugin.autotable-Chc3P4qR.js";import{D as Sa}from"./download-DeEr8--Q.js";import{P as Cn,a as kn}from"./PieChart-fj8ZfpAO.js";import{A as Rn,a as $n,b as An}from"./alert-DjXis0va.js";import{S as ut}from"./slider-Dp9zBjko.js";import{L as En}from"./lock-Bbp2ST9q.js";import{G as ea}from"./globe-ndGDO0lw.js";import{S as In}from"./share-2-Bta9uYt2.js";import{S as ha}from"./save-OJEKMKPX.js";import{A as Fn}from"./award-BOISaJ5W.js";import{W as Rs}from"./wallet-SwWcHjSV.js";import{i as Tn}from"./aiFunctionInvoke-Cs7ieDdZ.js";import{A as Dn,a as On,b as Bn,c as Wn,d as Ln,e as Yn,f as _n,g as zn}from"./alert-dialog-6hDSgLtb.js";import{E as Gn}from"./ellipsis-vertical-MvULMGKP.js";import{T as Un}from"./textarea-BcpY4LR0.js";import{A as Hn}from"./archive-ClJVw0B1.js";import{B as Vn}from"./bot-CqAt3G48.js";import{P as qn}from"./paperclip-nNnACa4S.js";import{P as Kn}from"./pencil-DJOgqgf2.js";import{A as $s}from"./arrow-up-CY38XiBd.js";import{A as As}from"./arrow-down-BtHDfmAE.js";import"./supabase-DAkTXe5u.js";import"./data-source-badge-DJyaLwyi.js";import"./hand-Cr4GOhEd.js";import"./freshness-label-B4ZzmTom.js";import"./differenceInDays-BzbxwdNJ.js";import"./index-DdjZJzOc.js";import"./color-9lF95FHy.js";import"./PolarAngleAxis-DkkDJ1ko.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const Es=ua("Baby",[["path",{d:"M9 12h.01",key:"157uk2"}],["path",{d:"M15 12h.01",key:"1k8ypt"}],["path",{d:"M10 16c.5.3 1.2.5 2 .5s1.5-.2 2-.5",key:"1u7htd"}],["path",{d:"M19 6.3a9 9 0 0 1 1.8 3.9 2 2 0 0 1 0 3.6 9 9 0 0 1-17.6 0 2 2 0 0 1 0-3.6A9 9 0 0 1 12 3c2 0 3.5 1.1 3.5 2.5s-.9 2.5-2 2.5c-.8 0-1.5-.4-1.5-1",key:"5yv0yz"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const Xn=ua("CodeXml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Zn=ua("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]),ta=({active:t,payload:x,label:s})=>t&&x&&x.length?e.jsxs("div",{className:"bg-card border border-border rounded-lg shadow-lg p-4",children:[e.jsx("p",{className:"font-medium text-foreground mb-2",children:s}),x.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:i.color}}),i.name]}),e.jsx("span",{className:"font-medium",children:i.name==="Patients"?i.value:A(i.value)})]},l))]}):null;function Jn({projections:t,yearlySummaries:x}){const s=t.map(u=>({name:u.date,revenue:u.totalRevenue,expenses:u.totalCOS+u.totalSGA,profit:u.netOperatingIncome,patients:u.endingPatients,cumulative:u.cumulativeProfit})),i=Math.max(0,Math.floor(s.length/12)-1),l=x.map(u=>({name:`Year ${u.year}`,revenue:u.totalRevenue,expenses:u.totalCOS+u.totalSGA,netIncome:u.netIncome,physicianComp:u.physicianTotalComp,patients:u.endingPatients}));return e.jsxs(me,{className:"animate-slide-up",style:{animationDelay:"100ms"},children:[e.jsx(Ce,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Je,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ae,{children:"Financial Projections"}),e.jsx(ke,{children:"Revenue, expenses, and profit visualization"})]})]})}),e.jsx(le,{children:e.jsxs(Na,{defaultValue:"yearly",className:"w-full",children:[e.jsxs(ba,{className:"mb-4",children:[e.jsxs(Ue,{value:"yearly",className:"gap-2",children:[e.jsx(Hs,{className:"h-4 w-4"}),"Annual"]}),e.jsxs(Ue,{value:"monthly",className:"gap-2",children:[e.jsx(Je,{className:"h-4 w-4"}),"Monthly Trend"]}),e.jsxs(Ue,{value:"patients",className:"gap-2",children:[e.jsx(Qe,{className:"h-4 w-4"}),"Patient Growth"]})]}),e.jsx(He,{value:"yearly",children:e.jsx("div",{className:"h-[400px] w-full",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(ot,{data:l,margin:{top:10,right:30,left:0,bottom:0},children:[e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"name",tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}
16,tickLine:!1,axisLine:!1}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickLine:!1,axisLine:!1,tickFormatter:u=>`$${(u/1e3).toFixed(0)}k`}),e.jsx(De,{content:e.jsx(ta,{})}),e.jsx(Ge,{}),e.jsx(ma,{y:0,stroke:"hsl(var(--muted-foreground))",strokeOpacity:.4}),e.jsx(be,{dataKey:"revenue",name:"Revenue",fill:"hsl(221, 83%, 53%)",radius:[4,4,0,0]}),e.jsx(be,{dataKey:"expenses",name:"Total Expenses",fill:"hsl(0, 70%, 60%)",radius:[4,4,0,0]}),e.jsx(be,{dataKey:"netIncome",name:"Net Income",fill:"hsl(160, 84%, 39%)",radius:[4,4,0,0]}),e.jsx(be,{dataKey:"physicianComp",name:"Physician Comp",fill:"hsl(250, 84%, 54%)",radius:[4,4,0,0]})]})})})}),e.jsx(He,{value:"monthly",children:e.jsx("div",{className:"h-[400px] w-full",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(Ps,{data:s,margin:{top:10,right:30,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorRevenue",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"hsl(221, 83%, 53%)",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"hsl(221, 83%, 53%)",stopOpacity:0})]})}),e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"name",tick:{fill:"hsl(var(--muted-foreground))",fontSize:11},tickLine:!1,axisLine:!1,interval:i}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickLine:!1,axisLine:!1,tickFormatter:u=>`$${(u/1e3).toFixed(0)}k`}),e.jsx(De,{content:e.jsx(ta,{})}),e.jsx(Ge,{}),e.jsx(ma,{y:0,stroke:"hsl(var(--muted-foreground))",strokeOpacity:.4}),e.jsx(is,{type:"monotone",dataKey:"revenue",name:"Revenue",stroke:"hsl(221, 83%, 53%)",fillOpacity:1,fill:"url(#colorRevenue)",strokeWidth:2}),e.jsx(Ze,{type:"monotone",dataKey:"expenses",name:"Expenses",stroke:"hsl(0, 70%, 60%)",strokeWidth:2,dot:!1}),e.jsx(Ze,{type:"monotone",dataKey:"profit",name:"Net Income",stroke:"hsl(160, 84%, 39%)",strokeWidth:2,dot:!1}),e.jsx(Ze,{type:"monotone",dataKey:"cumulative",name:"Cumulative Profit",stroke:"hsl(38, 92%, 50%)",strokeWidth:2,strokeDasharray:"5 5"})]})})})}),e.jsx(He,{value:"patients",children:e.jsx("div",{className:"h-[400px] w-full",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(yn,{data:s,margin:{top:10,right:30,left:0,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorPatients",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"hsl(250, 84%, 54%)",stopOpacity:.4}),e.jsx("stop",{offset:"95%",stopColor:"hsl(250, 84%, 54%)",stopOpacity:0})]})}),e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"name",tick:{fill:"hsl(var(--muted-foreground))",fontSize:11},tickLine:!1,axisLine:!1,interval:i}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickLine:!1,axisLine:!1}),e.jsx(De,{content:e.jsx(ta,{})}),e.jsx(Ge,{}),e.jsx(is,{type:"monotone",dataKey:"patients",name:"Patients",stroke:"hsl(250, 84%, 54%)",fillOpacity:1,fill:"url(#colorPatients)",strokeWidth:3})]})})})})]})})]})}const Qn=({active:t,payload:x})=>{if(t&&x&&x.length){const s=x[0].payload;return e.jsxs("div",{className:"bg-card border border-border rounded-lg shadow-lg p-3",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:s.name}),e.jsxs("p",{className:`text-sm font-semibold ${s.value>=0?"text-success":"text-destructive"}`,children:[A(Math.abs(s.value)),s.value<0&&" (expense)"]})]})}return null};function ei({yearlySummaries:t,selectedYear:x=1}){const s=t.find(u=>u.year===x)||t[0],l=F.useMemo(()=>{if(!s)return[];const u=s.totalRevenue-s.totalCOS,r=[];let d=0;return r.push({name:"Revenue",value:s.totalRevenue,start:0,end:s.totalRevenue,fill:"hsl(160, 84%, 39%)"}),d=s.totalRevenue,r.push({name:"Cost of Services",value:-s.totalCOS,start:d,end:d-s.totalCOS,fill:"hsl(0, 84%, 60%)"}),d-=s.totalCOS,r.push({name:"Gross Margin",value:u,start:0,end:u,fill:"hsl(221, 83%, 53%)",isTotal:!0}),r.push({name:"SG&A Expenses",value:-s.totalSGA,start:u,end:u-s.totalSGA,fill:"hsl(0, 84%, 60%)"}),r.push({name:"Net Income",value:s.netIncome,start:0,end:s.netIncome,fill:s.netIncome>=0?"hsl(160, 84%, 39%)":"hsl(0, 84%, 60%)",isTotal:!0}),r},[s]).map(u=>({name:u.name,value:u.value,invisible:u.isTotal?0:Math.min(u.start,u.end
16),bar:Math.abs(u.end-u.start),fill:u.fill,isTotal:u.isTotal,actualValue:u.value}));return e.jsxs(me,{className:"animate-slide-up",children:[e.jsxs(Ce,{children:[e.jsxs(Ae,{className:"text-lg",children:["P&L Waterfall - Year ",x]}),e.jsx(ke,{children:"How revenue flows to net income"})]}),e.jsxs(le,{children:[e.jsx("div",{className:"h-[300px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(ot,{data:l,margin:{top:20,right:30,left:20,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Ye,{dataKey:"name",tick:{fontSize:11},className:"text-muted-foreground"}),e.jsx(Oe,{tickFormatter:u=>`$${(u/1e3).toFixed(0)}k`,className:"text-muted-foreground"}),e.jsx(De,{content:e.jsx(Qn,{})}),e.jsx(ma,{y:0,stroke:"hsl(var(--muted-foreground))"}),e.jsx(be,{dataKey:"invisible",stackId:"stack",fill:"transparent"}),e.jsx(be,{dataKey:"bar",stackId:"stack",radius:[4,4,0,0],children:l.map((u,r)=>e.jsx(ws,{fill:u.fill,stroke:u.isTotal?"hsl(var(--foreground))":"none",strokeWidth:u.isTotal?2:0},`cell-${r}`))})]})})}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-4 mt-4 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"hsl(160, 84%, 39%)"}}),e.jsx("span",{className:"text-muted-foreground",children:"Revenue / Profit"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded",style:{backgroundColor:"hsl(0, 84%, 60%)"}}),e.jsx("span",{className:"text-muted-foreground",children:"Expenses (COS & SG&A)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded border-2 border-foreground",style:{backgroundColor:"hsl(221, 83%, 53%)"}}),e.jsx("span",{className:"text-muted-foreground",children:"Subtotals"})]})]})]})]})}function ti({explanations:t}){const x=i=>{switch(i){case"positive":return e.jsx(Je,{className:"h-4 w-4 text-success"});case"negative":return e.jsx(Pn,{className:"h-4 w-4 text-destructive"});default:return e.jsx(wn,{className:"h-4 w-4 text-muted-foreground"})}},s=i=>e.jsxs("span",{className:de("inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium",i==="positive"&&"bg-success/10 text-success",i==="negative"&&"bg-destructive/10 text-destructive",i==="neutral"&&"bg-muted text-muted-foreground"),children:[x(i),i==="positive"?"Favorable":i==="negative"?"Watch":"Neutral"]});return e.jsxs(me,{className:"animate-slide-up",style:{animationDelay:"200ms"},children:[e.jsx(Ce,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Vs,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ae,{children:"Projection Explanations"}),e.jsx(ke,{children:"Understand how each projection is calculated"})]})]})}),e.jsx(le,{children:e.jsx(vn,{type:"single",collapsible:!0,className:"w-full",children:t.map((i,l)=>e.jsxs(Nn,{value:`item-${l}`,children:[e.jsx(bn,{className:"hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left",children:[s(i.impact),e.jsx("span",{className:"font-medium",children:i.title})]})}),e.jsx(Sn,{children:e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:i.description}),i.formula&&e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-muted/50 border border-border",children:[e.jsx(Xn,{className:"h-5 w-5 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Formula"}),e.jsx("code",{className:"text-sm font-mono text-foreground",children:i.formula})]})]})]})})]},l))})})]})}function ai(t){return t==="pediatric"?{infant:"Infant (0-24 months)",child:"Toddler (2-6 years)",adult:"Youth (7-17 years)",senior:"Senior (N/A)",complex:"Complex/Special Needs",hideSenior:!0}:{infant:"Infant (0-2)",child:"Child (3-17)",adult:"Adult (18-64)",senior:"Senior (65+)",complex:"Complex",hideSenior:!1}}const N='"$"#,##0;[Red]("$"#,##0)',ze="0%",et="#,##0";function Ie(t){let x="",s=t;
16for(;s>=0;)x=String.fromCharCode(s%26+65)+x,s=Math.floor(s/26)-1;return x}function re(t,x,s=!1,i=!1){const l=i?`$${Ie(x)}`:Ie(x),u=s?`$${t+1}`:`${t+1}`;return`${l}${u}`}function B(t,x,s,i,l){const u=re(x,s);t[u]={t:"n",f:i},l&&(t[u].z=l)}function a(t,x,s,i,l){const u=re(x,s);typeof i=="number"?(t[u]={t:"n",v:i},l&&(t[u].z=l)):i!==null&&(t[u]={t:"s",v:i})}const o={clientName:11,startupDate:12,practiceModel:13,projectionYears:14,infantPrice:20,infantMix:21,childPrice:22,childMix:23,adultPrice:24,adultMix:25,seniorPrice:26,seniorMix:27,blendedPrice:28,enrollmentFee:29,patientsAtInception:35,growthRateM1_6:36,growthRateM7_12:37,growthRateY2Plus:38,enableAttrition:39,attritionRate:40,attritionStartMonth:41,enableMaxPanel:42,maxPanelSize:43,staffStartAtPatients:44,rent:50,staffWagesMonthly:51,fhManagementPackage:52,accountingMonthly:53,malpracticeInsurance:59,commercialInsurance:60,marketingAnnual:61,internetUtilities:62,duesSubscriptions:63,officeSupplies:64,printingSupplies:65,postage:66,travelMeals:67,otherOperating:68,paymentProcessingPercent:74,softwarePerPatient:75,cogsPerPatient:76,medicalSuppliesPerPatient:77,vaccinesMedicationsMargin:78,expenseGrowthRate:79,fhLaunchFee:85,facilityBuildout:86,furnitureFixtures:87,officeEquipment:88,securityDeposit:89,medicalEquipment:90,initialInventory:91,medicalSuppliesStartup:92,signageBranding:93,legalAccounting:94,startupMarketing:95,initialStaffTraining:96,totalStartupCosts:97,stipendPerMonth:103,fdNetworkFee:104,revenueSharePercent:105,enableProfitSplit:106,msoSplit:107};function Is(t){const x="results"in t?t.results:t,s="benchmarks"in t?t.benchmarks:void 0,{assumptions:i,yearlySummaries:l,monthlyProjections:u,peakCapitalDeployment:r,breakEvenMonth:d}=x,M=We.book_new(),b=i.practiceModel==="independent_dpc",c=i.enableAncillaryRevenue,p=u.some(f=>f.staffWages>0),E=i.practiceSpecialty==="pediatric",g=ai(i.practiceSpecialty),O=u.map(f=>f.date),v=u.length;l[0],l[1],l[l.length-1];const W={fhLaunchFee:i.fhLaunchFee||0,facilityBuildout:i.facilityBuildout||0,furnitureFixtures:i.furnitureFixtures||0,officeEquipment:i.officeEquipment||0,securityDeposit:i.securityDeposit||0,medicalEquipment:i.medicalEquipment||0,initialInventory:i.initialInventory||0,medicalSuppliesStartup:i.medicalSuppliesStartup||0,signageBranding:i.signageBranding||0,legalAccounting:i.legalAccounting||0,startupMarketing:i.startupMarketing||0,initialStaffTraining:i.initialStaffTraining||0},S=Object.values(W).reduce((f,k)=>f+k,0),n={};n["!ref"]="A1:E120",n["!cols"]=[{wch:32},{wch:18},{wch:20},{wch:14},{wch:10}],a(n,0,0,"FREEDOM HEALTHWORKS"),a(n,1,0,"MODEL ASSUMPTIONS (INPUT SHEET)"),a(n,2,0,"â ï¸ Edit values in column B to recalculate projections"),a(n,4,0,`Generated: ${new Date().toLocaleDateString()}`),a(n,7,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,8,0,"PRACTICE INFORMATION"),a(n,9,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.clientName,0,"Practice Name"),a(n,o.clientName,1,i.clientName),a(n,o.startupDate,0,"Start Date"),a(n,o.startupDate,1,i.startupDate),a(n,o.practiceModel,0,"Practice Model"),a(n,o.practiceModel,1,b?"Independent DPC":"FreedomDoc Health"),a(n,o.projectionYears,0,"Projection Years"),a(n,o.projectionYears,1,i.projectionYears),a(n,16,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,17,0,"AGE-BASED MEMBERSHIP PRICING"),a(n,18,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.infantPrice,0,`${g.infant} Price/Month`),a(n,o.infantPrice,1,i.infantPricePerMonth||0,N),a(n,o.infantMix,0,"Infant Mix %"),a(n,o.infantMix,1,i.infantWeighting||0,ze),a(n,o.childPrice,0,`${g.child} Price/Month`),a(n,o.childPrice,1,i.childPricePerMonth,N),a(n,o.childMix,0,"Child Mix %"),a(n,o.childMix,1,i.childWeighting||0,ze),a(n,o.adultPrice,0,`${g.adult} Price/Month`),a(n,o.adultPrice,1,i.adultPricePerMonth,N),a(n,o.adultMix,0,`${E?"Youth":"Adult"} Mix %`),a(n,o.adultMix,1,i.adultWeighting||0,ze),E||(a(n,o.seniorPrice,0,`${g.senior} Price/Month`),a(n,o.seniorPrice,1,i.seniorPricePerMonth||0,N),a(n,o.seniorMix,0,"Senior Mix %"),a(n,o.seniorMix,1,i.seniorWeighting||0,ze)),a(n,o.blendedPrice,0,"Blended Price/Month");const X=E?`(B${o.infantPrice+1}*B${o.infantMix+1})+(B${o.childPrice+1}*B${o.childMix+1})+(B${o.adultPrice+1}*B${o.adultMix+1})`:`(B${o.infantPrice+1}*B${o.infantMix+1})+(B${o.childPrice+1}*B${o.childMix+1})+(B${o.adultPrice+1}*B${o.adultMix+1})+(B${o.seniorPrice+1}*B${o.seniorMix+1})`;B(n,o.blendedPrice,1,X,N),a(n,o.enrollmentFee,0,"Enrollment Fee (One-Time)"),a(n,o.enrollmentFee,1,i.enrollmentFee,N),a(n,31,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,32,0,"PATIENT GROWTH ASSUMPTIONS"),a(n,33,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.patientsAtInception,0,"Pre-Enrolled Patients"),a(n,o.patientsAtInception,1,i.patientsAtInception),a(n,o.growthRateM1_6,0,"Growth Rate (Months 1-6)"),a(n,o.growthRateM1_6,1,i.growthRateMonths1to6),a(n,o.growthRateM7_12,0,"Growth Rate (Months 7-12)"),a(n,o.growthRateM7_12,1,i.growthRateMonths7to12),a(n,o.growthRateY2Plus,0,"Growth Rate (Year 2+)"),a(n,o.growthRateY2Plus,1,i.growthRateYear2Plus),a(n,o.enableAttrition,0,"Attrition Enabled"),a(n,o.enableAttrition,1,i.enableAttrition?1:0),a(n,o.attritionRate,0,"Attrition Rate (Annual %)"),a(n,o.attritionRate,1,i.attritionRate/100,ze),a(n,o.attritionStartMonth,0,"Attrition Start Month"),a(n,o.attritionStartMonth,1,i.attritionStartMonth),a(n,o.enableMaxPanel,0,"Max Panel Enabled"),a(n,o.enableMaxPanel,1,i.enableMaxPanel?1:0),a(n,o.maxPanelSize,0,"Max Panel Size"),a(n,o.maxPanelSize,1,i.maxPatientPanel),a(n,o.staffStartAtPatients,0,"Staff Start at Patients"),a(n,o.staffStartAtPatients,1,i.staffStartAtPatients),a(n,46,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,47,0,"MONTHLY OPERATING EXPENSES"),a(n,48,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.rent,0,"Rent/Facility (Monthly)"),a(n,o.rent,1,i.rent,N),a(n,o.staffWagesMonthly,0,"Staff Wages (Monthly)"),a(n,o.staffWagesMonthly,1,i.staffWagesMonthly,N),a(n,o.fhManagementPackage,0,"FH Operations Package (Monthly)"),a(n,o.fhManagementPackage,1,i.fhManagementPackage,N),a(n,o.accountingMonthly,0,"Accounting/Bookkeeping (Monthly)"),a(n,o.accountingMonthly,1,i.accountingMonthly,N),a(n,55,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,56,0,"ANNUAL OPERATING EXPENSES"),a(n,57,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.malpracticeInsurance,0,"Malpractice Insurance (Annual)"),a(n,o.malpracticeInsurance,1,i.malpracticeInsurance,N),a(n,o.commercialInsurance,0,"Commercial Insurance (Annual)"),a(n,o.commercialInsurance,1,i.commercialInsurance,N),a(n,o.marketingAnnual,0,"Marketing (Annual)"),a(n,o.marketingAnnual,1,i.marketing,N),a(n,o.internetUtilities,0,"Internet & Utilities (Annual)"),a(n,o.internetUtilities,1,i.internetUtilities,N),a(n,o.duesSubscriptions,0,"Dues & Subscriptions (Annual)"),a(n,o.duesSubscriptions,1,i.duesBoardsSubscriptions,N),a(n,o.officeSupplies,0,"Office Supplies (Annual)"),a(n,o.officeSupplies,1,i.officeSupplies,N),a(n,o.printingSupplies,0,"Printing Supplies (Annual)"),a(n,o.printingSupplies,1,i.printingSupplies,N),a(n,o.postage,0,"Postage (Annual)"),a(n,o.postage,1,i.postage,N),a(n,o.travelMeals,0,"Travel & Meals (Annual)"),a(n,o.travelMeals,1,i.travelMeals,N),a(n,o.otherOperating,0,"Other Operating (Annual)"),a(n,o.otherOperating,1,i.otherOperating,N),a(n,70,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,71,0,"VARIABLE COSTS & RATES"),a(n,72,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.paymentProcessingPercent,0,"Payment Processing %"),a(n,o.paymentProcessingPercent,1,i.paymentProcessingPercent/100,ze),a(n,o.softw
16arePerPatient,0,"Software/EMR per Patient"),a(n,o.softwarePerPatient,1,i.softwarePerPatient,N),a(n,o.cogsPerPatient,0,"COGS per Patient"),a(n,o.cogsPerPatient,1,i.cogsPerPatient,N),a(n,o.medicalSuppliesPerPatient,0,"Medical Supplies per Patient"),a(n,o.medicalSuppliesPerPatient,1,i.medicalSuppliesPerPatient,N),a(n,o.vaccinesMedicationsMargin,0,"Vaccines/Medications Margin %"),a(n,o.vaccinesMedicationsMargin,1,i.vaccinesMedicationsMargin/100,ze),a(n,o.expenseGrowthRate,0,"Annual Expense Growth Rate"),a(n,o.expenseGrowthRate,1,i.expenseGrowthRate/100,ze),a(n,81,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,82,0,"STARTUP COSTS (One-Time)"),a(n,83,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.fhLaunchFee,0,"FH Launch Fee"),a(n,o.fhLaunchFee,1,W.fhLaunchFee,N),a(n,o.facilityBuildout,0,"Facility Buildout"),a(n,o.facilityBuildout,1,W.facilityBuildout,N),a(n,o.furnitureFixtures,0,"Furniture & Fixtures"),a(n,o.furnitureFixtures,1,W.furnitureFixtures,N),a(n,o.officeEquipment,0,"Office Equipment"),a(n,o.officeEquipment,1,W.officeEquipment,N),a(n,o.securityDeposit,0,"Security Deposit"),a(n,o.securityDeposit,1,W.securityDeposit,N),a(n,o.medicalEquipment,0,"Medical Equipment"),a(n,o.medicalEquipment,1,W.medicalEquipment,N),a(n,o.initialInventory,0,"Initial Inventory"),a(n,o.initialInventory,1,W.initialInventory,N),a(n,o.medicalSuppliesStartup,0,"Medical Supplies (Startup)"),a(n,o.medicalSuppliesStartup,1,W.medicalSuppliesStartup,N),a(n,o.signageBranding,0,"Signage & Branding"),a(n,o.signageBranding,1,W.signageBranding,N),a(n,o.legalAccounting,0,"Legal & Accounting"),a(n,o.legalAccounting,1,W.legalAccounting,N),a(n,o.startupMarketing,0,"Startup Marketing"),a(n,o.startupMarketing,1,W.startupMarketing,N),a(n,o.initialStaffTraining,0,"Initial Staff Training"),a(n,o.initialStaffTraining,1,W.initialStaffTraining,N),a(n,o.totalStartupCosts,0,"TOTAL STARTUP COSTS"),B(n,o.totalStartupCosts,1,`SUM(B${o.fhLaunchFee+1}:B${o.initialStaffTraining+1})`,N),b||(a(n,99,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,100,0,"FREEDOMDOC HEALTH SPECIFIC"),a(n,101,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(n,o.stipendPerMonth,0,"Monthly Stipend"),a(n,o.stipendPerMonth,1,i.stipendPerMonth,N),a(n,o.fdNetworkFee,0,"FD Network Fee"),a(n,o.fdNetworkFee,1,i.fdNetworkFee,N),a(n,o.revenueSharePercent,0,"Revenue Share %"),a(n,o.revenueSharePercent,1,i.revenueSharePercent/100,ze),a(n,o.enableProfitSplit,0,"Profit Split Enabled"),a(n,o.enableProfitSplit,1,i.enableProfitSplit?1:0),a(n,o.msoSplit,0,"MSO Split %"),a(n,o.msoSplit,1,i.msoSplit/100,ze)),We.book_append_sheet(M,n,"Assumptions");const y={},_=v+1;y["!ref"]=`A1:${Ie(_)}60`,y["!cols"]=[{wch:28},...O.map(()=>({wch:12}))];let w=0;a(y,w++,0,"FREEDOM HEALTHWORKS - MONTHLY P&L PROJECTION"),a(y,w++,0,i.clientName),a(y,w++,0,`Practice Model: ${b?"Independent DPC":"FreedomDoc Health"}`),a(y,w++,0,`Generated: ${new Date().toLocaleDateString()}`),w++;const h=w++;a(y,h,0,"Account");for(let f=0;f<v;f++)a(y,h,f+1,O[f]);w++;const T=w++;a(y,T,0,"PATIENTS");const U=w++;a(y,U,0," Beginning Patients");const j=w++;a(y,j,0," New Patients");const R=w++;a(y,R,0," Attrition");const H=w++;a(y,H,0," Ending Patients");for(let f=0;f<v;f++){const k=f+1;u[f];const ye=f+1;f===0?B(y,U,k,`Assumptions!$B$${o.patientsAtInception+1}
16`,et):B(y,U,k,re(H,k-1),et);let ie;ye<=6?ie=`Assumptions!$B$${o.growthRateM1_6+1}`:ye<=12?ie=`Assumptions!$B$${o.growthRateM7_12+1}`:ie=`Assumptions!$B$${o.growthRateY2Plus+1}`;const je=`IF(Assumptions!$B$${o.enableMaxPanel+1}=1,MIN(${ie},MAX(0,Assumptions!$B$${o.maxPanelSize+1}-${re(U,k)})),${ie})`;B(y,j,k,je,et);const $e=`IF(AND(Assumptions!$B$${o.enableAttrition+1}=1,${ye}>=Assumptions!$B$${o.attritionStartMonth+1}),-ROUND(${re(U,k)}*Assumptions!$B$${o.attritionRate+1}/12,0),0)`;B(y,R,k,$e,et),B(y,H,k,`${re(U,k)}+${re(j,k)}+${re(R,k)}`,et)}w++;const ee=w++;a(y,ee,0,"REVENUE");const z=w++;a(y,z,0," Membership Revenue");const C=w++;a(y,C,0," Enrollment Fees");const K=w++;a(y,K,0," Vaccines & Medications");let Q=null;c&&(Q=w++,a(y,Q,0," Ancillary Services"));const G=w++;a(y,G,0,"TOTAL REVENUE");for(let f=0;f<v;f++){const k=f+1,ye=u[f];B(y,z,k,`${re(H,k)}*Assumptions!$B$${o.blendedPrice+1}`,N),B(y,C,k,`${re(j,k)}*Assumptions!$B$${o.enrollmentFee+1}`,N),a(y,K,k,ye.vaccinesMedications,N),c&&Q!==null&&a(y,Q,k,ye.ancillaryRevenue,N);const ie=c&&Q!==null?`SUM(${re(z,k)}:${re(Q,k)})`:`SUM(${re(z,k)}:${re(K,k)})`;B(y,G,k,ie,N)}w++;const te=w++;a(y,te,0,"COST OF SERVICES");let Z=null;b||(Z=w++,a(y,Z,0," Physician Wages"));let m=null;p&&(m=w++,a(y,m,0," Staff Wages"));const Y=w++;a(y,Y,0," FH Operations Package");const L=w++;a(y,L,0," Cost of Goods Sold");const D=w++;a(y,D,0," Medical Supplies");let se=null;c&&(se=w++,a(y,se,0," Ancillary Costs"));const fe=w++;a(y,fe,0,"TOTAL COST OF SERVICES");for(let f=0;f<v;f++){const k=f+1,ye=u[f],ie=Math.ceil((f+1)/12),je=ie>1?`(1+Assumptions!$B$${o.expenseGrowthRate+1})^${ie-1}`:"1";if(!b&&Z!==null&&B(y,Z,k,`Assumptions!$B$${o.stipendPerMonth+1}*${je}`,N),p&&m!==null){const Be=`IF(${re(H,k)}>=Assumptions!$B$${o.staffStartAtPatients+1},Assumptions!$B$${o.staffWagesMonthly+1}*${je},0)`;B(y,m,k,Be,N)}B(y,Y,k,`Assumptions!$B$${o.fhManagementPackage+1}*${je}`,N),B(y,L,k,`${re(H,k)}*Assumptions!$B$${o.cogsPerPatient+1}*${je}`,N),B(y,D,k,`${re(H,k)}*Assumptions!$B$${o.medicalSuppliesPerPatient+1}*${je}`,N),c&&se!==null&&a(y,se,k,ye.ancillaryCosts,N);const $e=!b&&Z!==null?Z:p&&m!==null?m:Y,_e=c&&se!==null?se:D;B(y,fe,k,`SUM(${re($e,k)}:${re(_e,k)})`,N)}w++;const P=w++;a(y,P,0,"GROSS MARGIN");for(let f=0;f<v;f++){const k=f+1;B(y,P,k,`${re(G,k)}-${re(fe,k)}`,N)}w++;const ue=w++;a(y,ue,0,"OPERATING EXPENSES (SG&A)");let oe=null,Pe=null;b||(oe=w++,a(y,oe,0," MSO Network Fee"),Pe=w++,a(y,Pe,0," Revenue Share"));const Ee=w++;a(y,Ee,0," Facility/Rent");const it=w++;a(y,it,0," Malpractice Insurance");const wa=w++;a(y,wa,0," Commercial Insurance");const Pa=w++;a(y,Pa,0," Marketing");const Ma=w++;a(y,Ma,0," Dues & Subscriptions");const Ca=w++;a(y,Ca,0," Payment Processing");const ka=w++;a(y,ka,0," Internet & Utilities");const Ra=w++;a(y,Ra,0," Software/EMR");const $a=w++;a(y,$a,0," Accounting");const Aa=w++;a(y,Aa,0," Printing & Supplies");const Ea=w++;a(y,Ea,0," Postage");const Ia=w++;a(y,Ia,0," Travel & Meals");const Fa=w++;a(y,Fa,0," Office Supplies");const Ut=w++;a(y,Ut,0," Other Operating");const vt=w++;a(y,vt,0,"TOTAL SG&A");for(let f=0;f<v;f++){const k=f+1;u[f];const ye=Math.ceil((f+1)/12),ie=ye>1?`(1+Assumptions!$B$${o.expenseGrowthRate+1})^${ye-1}`:"1";!b&&oe!==null&&Pe!==null&&(B(y,oe,k,`Assumptions!$B$${o.fdNetworkFee+1}*${ie}`,N),B(y,Pe,k,`${re(G,k)}*Assumptions!$B$${o.revenueSharePercent+1}`,N)),B(y,Ee,k,`Assumptions!$B$${o.rent+1}*${ie}`,N),B(y,it,k,`Assumptions!$B$${o.malpracticeInsurance+1}/12*${ie}`,N),B(y,wa,k,`Assumptions!$B$${o.commercialInsurance+1}/12*${ie}`,N),B(y,Pa,k,`Assumptions!$B$${o.marketingAnnual+1}/12*${ie}`,N),B(y,Ma,k,`Assumptions!$B$${o.duesSubscriptions+1}/12*${ie}`,N),B(y,Ca,k,`${re(G,k)}*Assumptions!$B$${o.paymentProcessingPercent+1}`,N),B(y,ka,k,`Assumptions!$B$${o.internetUtilities+1}/12*${ie}`,N),B(y,Ra,k,`${re(H,k)}*Assumptions!$B$${o.softwarePerPatient+1}*${ie}`,N),B(y,$a,k,`Assumptions!$B$${o.accountingMonthly+1}*${ie}`,N),B(y,Aa,k,`Assumptions!$B$${o.printingSupplies+1}/12*${ie}`,N),B(y,Ea,k,`Assumptions!$B$${o.postage+1}/12*${ie}`,N),B(y,Ia,k,`Assumptions!$B$${o.travelMeals+1}/12*${ie}`,N),B(y,Fa,k,`Assumptions!$B$${o.officeSupplies+1}/12*${ie}`,N),B(y,Ut,k,`Assumptions!$B$${o.otherOperating+1}/12*${ie}`,N),B(y,vt,k,`SUM(${re(!b&&oe!==null?oe:Ee,k)}:${re(Ut,k)})`,N)}w++;const ht=w++;a(y,ht,0,"NET OPERATING INCOME");const qe=w++;a(y,qe,0,"CUMULATIVE P&L");for(let f=0;f<v;f++){const k=f+1;B(y,ht,k,`${re(P,k)}-${re(vt,k)}`,N),f===0?B(y,qe,k,`${re(ht,k)}-Assumptions!$B$${o.totalStartupCosts+1}`,N):B(y,qe,k,`${re(qe,k-1)}+${re(ht,k)}`,N)}y["!ref"]=`A1:${Ie(_)}${w+5}`,y["!freeze"]={xSplit:1,ySplit:h+1},We.book_append_sheet(M,y,"Monthly P&L");const $={};$["!ref"]="A1:D50",$["!cols"]=[{wch:32},{wch:16},{wch:16},{wch:16}];let q=0;
16a($,q++,0,"FREEDOM HEALTHWORKS"),a($,q++,0,"3-YEAR PROFIT & LOSS STATEMENT"),q++,a($,q++,0,i.clientName),a($,q++,0,`Practice Model: ${b?"Independent DPC":"FreedomDoc Health"}`),a($,q++,0,`Generated: ${new Date().toLocaleDateString()}`),q++,q++;const Nt=q++;a($,Nt,0,""),a($,Nt,1,"Year 1"),a($,Nt,2,"Year 2"),a($,Nt,3,"Year 3");const Re=(f,k)=>{const ye=(k-1)*12+1,ie=Math.min(k*12,v);if(ye>v)return"0";const je=Ie(ye),$e=Ie(ie);return`SUM('Monthly P&L'!${je}${f+1}:${$e}${f+1})`};if(S>0){const f=q++;a($,f,0,"STARTUP COSTS (One-Time)");const k=q++;a($,k,0," FH Launch Fee"),B($,k,1,`-Assumptions!$B$${o.fhLaunchFee+1}`,N),a($,k,2,0,N),a($,k,3,0,N);const ye=q++;a($,ye,0," Furniture & Fixtures"),B($,ye,1,`-Assumptions!$B$${o.furnitureFixtures+1}`,N),a($,ye,2,0,N),a($,ye,3,0,N);const ie=q++;a($,ie,0," Office Equipment"),B($,ie,1,`-Assumptions!$B$${o.officeEquipment+1}`,N),a($,ie,2,0,N),a($,ie,3,0,N);const je=q++;a($,je,0," Security Deposit"),B($,je,1,`-Assumptions!$B$${o.securityDeposit+1}`,N),a($,je,2,0,N),a($,je,3,0,N);const $e=q++;a($,$e,0," Medical Equipment"),B($,$e,1,`-Assumptions!$B$${o.medicalEquipment+1}`,N),a($,$e,2,0,N),a($,$e,3,0,N);const _e=q++;a($,_e,0," Initial Inventory"),B($,_e,1,`-Assumptions!$B$${o.initialInventory+1}`,N),a($,_e,2,0,N),a($,_e,3,0,N);const Be=q++;a($,Be,0," Medical Supplies (Startup)"),B($,Be,1,`-Assumptions!$B$${o.medicalSuppliesStartup+1}`,N),a($,Be,2,0,N),a($,Be,3,0,N);const rt=q++;a($,rt,0," Signage & Branding"),B($,rt,1,`-Assumptions!$B$${o.signageBranding+1}`,N),a($,rt,2,0,N),a($,rt,3,0,N);const wt=q++;a($,wt,0," Legal & Accounting"),B($,wt,1,`-Assumptions!$B$${o.legalAccounting+1}`,N),a($,wt,2,0,N),a($,wt,3,0,N);const Pt=q++;a($,Pt,0," Startup Marketing"),B($,Pt,1,`-Assumptions!$B$${o.startupMarketing+1}`,N),a($,Pt,2,0,N),a($,Pt,3,0,N);const Mt=q++;a($,Mt,0," Initial Staff Training"),B($,Mt,1,`-Assumptions!$B$${o.initialStaffTraining+1}`,N),a($,Mt,2,0,N),a($,Mt,3,0,N);const Ct=q++;a($,Ct,0,"Total Startup Costs"),B($,Ct,1,`-Assumptions!$B$${o.totalStartupCosts+1}`,N),a($,Ct,2,0,N),a($,Ct,3,0,N),q++}const Ts=q++;a($,Ts,0,"PATIENT METRICS");const Ht=q++;a($,Ht,0," Ending Patients");for(let f=1;f<=3;f++){const k=Math.min(f*12,v);k>0&&B($,Ht,f,`'Monthly P&L'!${Ie(k)}${H+1}`,et)}q++;const Ds=q++;a($,Ds,0,"REVENUE");const Ta=q++;a($,Ta,0," Membership Revenue");for(let f=1;f<=3;f++)B($,Ta,f,Re(z,f),N);const Da=q++;a($,Da,0," Enrollment Fees");for(let f=1;f<=3;f++)B($,Da,f,Re(C,f),N);const Oa=q++;a($,Oa,0," Vaccines & Medications");for(let f=1;f<=3;f++)B($,Oa,f,Re(K,f),N);let Vt=null;if(c&&Q!==null){Vt=q++,a($,Vt,0," Ancillary Services");for(let f=1;f<=3;f++)B($,Vt,f,Re(Q,f),N)}const bt=q++;a($,bt,0,"TOTAL REVENUE");for(let f=1;f<=3;f++)B($,bt,f,Re(G,f),N);q++;const Os=q++;if(a($,Os,0,"COST OF SERVICES"),!b&&Z!==null){const f=q++;a($,f,0," Physician Wages");for(let k=1;k<=3;k++)B($,f,k,Re(Z,k),N)}if(p&&m!==null){const f=q++;a($,f,0," Staff Wages");for(let k=1;k<=3;k++)B($,f,k,Re(m,k),N)}const Ba=q++;a($,Ba,0," FH Operations Package");for(let f=1;f<=3;f++)B($,Ba,f,Re(Y,f),N);const Wa=q++;a($,Wa,0," Cost of Goods Sold");for(let f=1;f<=3;f++)B($,Wa,f,Re(L,f),N);const La=q++;a($,La,0," Medical Supplies");for(let f=1;f<=3;f++)B($,La,f,Re(D,f),N);if(c&&se!==null){const f=q++;a($,f,0," Ancillary Costs");for(let k=1;k<=3;k++)B($,f,k,Re(se,k),N)}const qt=q++;a($,qt,0,"TOTAL COST OF SERVICES");for(let f=1;f<=3;f++)B($,qt,f,Re(fe,f),N);q++;const Ya=q++;a($,Ya,0,"GROSS MARGIN");for(let f=1;f<=3;f++)B($,Ya,f,`${re(bt,f)}-${re(qt,f)}`,N);q++;const Bs=q++;a($,Bs,0,"OPERATING EXPENSES (SG&A)");const _a=q++;a($,_a,0,"TOTAL SG&A");for(let f=1;f<=3;f++)B($,_a,f,Re(vt,f),N);q++;const Kt=q++;a($,Kt,0,"NET OPERATING INCOME");for(let f=1;f<=3;f++)B($,Kt,f,Re(ht,f),N);$["!ref"]=`A1:D${q+2}`,We.book_append_sheet(M,$,"3-Year P&L");const J={};J["!ref"]="A1:D40",J["!cols"]=[{wch:32},{wch:18},{wch:18},{wch:32}];let ne=0;a(J,ne++,0,"FREEDOM HEALTHWORKS"),a(J,ne++,0,"EXECUTIVE DASHBOARD"),ne++,a(J,ne++,0,i.clientName),a(J,ne++,0,`Practice Model: ${b?"Independent DPC":"FreedomDoc Health"}`),a(J,ne++,0,`Generated: ${new Date().toLocaleDateString()}`),ne++,ne++,a(J,ne++,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(J,ne++,0,"KEY PERFORMANCE METRICS"),a(J,ne++,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),ne++;const St=ne++;a(J,St,0,""),a(J,St,1,"Year 1"),a(J,St,2,"Year 2"),a(J,St,3,"Year 3");const za=ne++;a(J,za,0,"Ending Patients");for(let f=1;f<=3;f++)B(J,za,f,`'3-Year P&L'!${Ie(f)}
16${Ht+1}`,et);const Ga=ne++;a(J,Ga,0,"Total Revenue");for(let f=1;f<=3;f++)B(J,Ga,f,`'3-Year P&L'!${Ie(f)}${bt+1}`,N);const Ua=ne++;a(J,Ua,0,"Net Operating Income");for(let f=1;f<=3;f++)B(J,Ua,f,`'3-Year P&L'!${Ie(f)}${Kt+1}`,N);ne++,ne++,a(J,ne++,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(J,ne++,0,"CRITICAL FINANCIAL MILESTONES"),a(J,ne++,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),ne++;const Xt=ne++;a(J,Xt,0,"Peak Capital Required"),B(J,Xt,1,`MIN('Monthly P&L'!B${qe+1}:${Ie(v)}${qe+1})`,N),a(J,Xt,3,"â Maximum cash needed before profitability");const Ha=ne++;a(J,Ha,0,"Break-Even Month");const Ws=`IFERROR(MATCH(TRUE,INDIRECT("'Monthly P&L'!B${qe+1}:${Ie(v)}${qe+1}")>0,0),"N/A")`;B(J,Ha,1,Ws);const Zt=ne++;a(J,Zt,0,"Total Startup Investment"),B(J,Zt,1,`Assumptions!$B$${o.totalStartupCosts+1}`,N),a(J,Zt,3,"â One-time costs to launch"),ne++,ne++,a(J,ne++,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),a(J,ne++,0,"PRICING MODEL"),a(J,ne++,0,"âââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââââ"),ne++;const Jt=ne++;a(J,Jt,0,"Blended Price/Month"),B(J,Jt,1,`Assumptions!$B$${o.blendedPrice+1}`,N),a(J,Jt,3,"â Weighted average");const Va=ne++;a(J,Va,0,"Enrollment Fee"),B(J,Va,1,`Assumptions!$B$${o.enrollmentFee+1}`,N),J["!ref"]=`A1:D${ne+2}`,We.book_append_sheet(M,J,"Executive Dashboard");const Ls=["Executive Dashboard","Assumptions","Monthly P&L","3-Year P&L"];if(M.SheetNames=Ls,s&&s.length>0){const f=s.filter(k=>k.practice_type===(b?"independent_dpc":"freedomdoc_health"));if(f.length>0){const ye=($e=>{const _e=$e.filter(Be=>Be!=null);return _e.length>0?_e.reduce((Be,rt)=>Be+rt,0)/_e.length:null})(f.map($e=>$e.blended_price_per_month)),ie=[["FREEDOM HEALTHWORKS"],["BENCHMARK COMPARISON"],[],[i.clientName],[],[`Based on ${f.length} comparable practices`],[],["Metric","Your Practice","Industry Avg","Notes"],["Blended Price/Month",null,ye,"Compare to your Assumptions sheet"]],je=We.aoa_to_sheet(ie);je["!cols"]=[{wch:28},{wch:16},{wch:16},{wch:20}],je.B9={t:"n",f:`Assumptions!$B$${o.blendedPrice+1}`,z:N},je.C9&&typeof je.C9.v=="number"&&(je.C9.z=N),We.book_append_sheet(M,je,"Benchmark Comparison")}}const Ys=[["FREEDOM HEALTHWORKS"],["IMPORTANT DISCLAIMER"],[],[],["NOTES & DISCLAIMERS"],[],["This spreadsheet contains LIVE FORMULAS that recalculate when you modify the Assumptions sheet."],[],["To update projections:"],[' 1. Go to the "Assumptions" tab'],[" 2. Edit values in Column B"],[" 3. All other sheets will automatically recalculate"],[],["These estimates are based on stated assumptions and are not warranted or guaranteed in any way."],[],["Model assumes standard Freedom Healthworks services at time of calculation."],[],["Individual physician decisions and services do impact net results."],[],["Market conditions can vary and impact practice performance unfavorably or favorably."],[],["Estimates are for general informational purposes only."],[],[],["This projection was generated on: "+new Date().toLocaleString()]],qa=We.aoa_to_sheet(Ys);qa["!cols"]=[{wch:80}],We.book_append_sheet(M,qa,"Disclaimer");const _s=i.clientName.replace(/[^a-zA-Z0-9]/g,"_").substring(0,30)||"Practice",zs=new Date().toISOString().split("T")[0],Gs=`${_s}_Financial_Projection_${zs}.xlsx`;Mn(M,Gs)}function si({results:t}){const{assumptions:x,monthlyProjections:s,yearlySummaries:i}=t,l=x.practiceModel==="independent_dpc",u=P=>i.map((ue,oe)=>s.filter(Ee=>Ee.year===oe+1).reduce((Ee,it)=>
16Ee+P(it),0)),r=u(P=>P.membershipRevenue),d=u(P=>P.enrollmentFees),M=u(P=>P.vaccinesMedications),b=u(P=>P.ancillaryRevenue),c=u(P=>P.totalRevenue),p=u(P=>P.physicianWages),E=u(P=>P.staffWages),g=u(P=>P.fhOperationsPackage),O=u(P=>P.cogs),v=u(P=>P.medicalSupplies),W=u(P=>P.ancillaryCosts),S=u(P=>P.totalCOS),n=u(P=>P.grossMargin),X=u(P=>P.msoNetworkFee),y=u(P=>P.facilityExpense),_=u(P=>P.revenueShare),w=u(P=>P.malpracticeInsurance),h=u(P=>P.commercialInsurance),T=u(P=>P.duesBoardsSubscriptions),U=u(P=>P.marketing),j=u(P=>P.paymentProcessing),R=u(P=>P.internetUtilities),H=u(P=>P.software),ee=u(P=>P.printingSupplies),z=u(P=>P.postage),C=u(P=>P.travelMeals),K=u(P=>P.officeSupplies),Q=u(P=>P.otherOperating),G=u(P=>P.accounting),te=u(P=>P.totalSGA),Z=u(P=>P.netOperatingIncome),m={fhLaunchFee:x.fhLaunchFee||0,facilityBuildout:x.facilityBuildout||0,furnitureFixtures:x.furnitureFixtures||0,officeEquipment:x.officeEquipment||0,securityDeposit:x.securityDeposit||0,medicalEquipment:x.medicalEquipment||0,initialInventory:x.initialInventory||0,medicalSuppliesStartup:x.medicalSuppliesStartup||0,signageBranding:x.signageBranding||0,legalAccounting:x.legalAccounting||0,startupMarketing:x.startupMarketing||0,initialStaffTraining:x.initialStaffTraining||0},Y=Object.values(m).reduce((P,ue)=>P+ue,0),L=P=>i.map((ue,oe)=>oe===0?P:0),D=[];if(Y>0&&(D.push({label:"STARTUP COSTS (One-Time)",values:[],isSubtotal:!0}),m.fhLaunchFee>0&&D.push({label:"FH Launch Fee",values:L(m.fhLaunchFee),isExpense:!0,indent:1}),m.facilityBuildout>0&&D.push({label:"Facility Buildout",values:L(m.facilityBuildout),isExpense:!0,indent:1}),m.furnitureFixtures>0&&D.push({label:"Furniture & Fixtures",values:L(m.furnitureFixtures),isExpense:!0,indent:1}),m.officeEquipment>0&&D.push({label:"Office Equipment",values:L(m.officeEquipment),isExpense:!0,indent:1}),m.securityDeposit>0&&D.push({label:"Security Deposit",values:L(m.securityDeposit),isExpense:!0,indent:1}),m.medicalEquipment>0&&D.push({label:"Medical Equipment",values:L(m.medicalEquipment),isExpense:!0,indent:1}),m.initialInventory>0&&D.push({label:"Initial Inventory",values:L(m.initialInventory),isExpense:!0,indent:1}),m.medicalSuppliesStartup>0&&D.push({label:"Medical Supplies (Startup)",values:L(m.medicalSuppliesStartup),isExpense:!0,indent:1}),m.signageBranding>0&&D.push({label:"Signage & Branding",values:L(m.signageBranding),isExpense:!0,indent:1}),m.legalAccounting>0&&D.push({label:"Legal & Accounting",values:L(m.legalAccounting),isExpense:!0,indent:1}),m.startupMarketing>0&&D.push({label:"Startup Marketing",values:L(m.startupMarketing),isExpense:!0,indent:1}),m.initialStaffTraining>0&&D.push({label:"Initial Staff Training",values:L(m.initialStaffTraining),isExpense:!0,indent:1}),D.push({label:"Total Startup Costs",values:L(Y),isSubtotal:!0,isExpense:!0},{label:"",values:[]})),D.push({label:"REVENUE",values:[],isSubtotal:!0},{label:"Membership Revenue",values:r,indent:1},{label:"Enrollment Fees",values:d,indent:1},{label:"Vaccines & Medications",values:M,indent:1}),x.enableAncillaryRevenue&&D.push({label:"Ancillary Services",values:b,indent:1}),D.push({label:"Total Revenue",values:c,isSubtotal:!0},{label:"",values:[]},{label:"COST OF SERVICES",values:[],isSubtotal:!0}),l||D.push({label:"Physician Wages",values:p,isExpense:!0,indent:1}),E.some(P=>P>0)&&D.push({label:"Staff Wages",values:E,isExpense:!0,indent:1}),D.push({label:"FH Operations Package",values:g,isExpense:!0,indent:1},{label:"Cost of Goods Sold",values:O,isExpense:!0,indent:1},{label:"Medical Supplies",values:v,isExpense:!0,indent:1}),x.enableAncillaryRevenue&&D.push({label:"Ancillary Costs",values:W,isExpense:!0,indent:1}),D.push({label:"Total Cost of Services",values:S,isSubtotal:!0,isExpense:!0},{label:"",values:[]},{label:"GROSS MARGIN",values:n,isSubtotal:!0},{label:"",values:[]},{label:"OPERATING EXPENSES (SG&A)",values:[],isSubtotal:!0}),l||D.push({label:"MSO Network Fee",values:X,isExpense:!0,indent:1},{label:"Revenue Share",values:_,isExpense:!0,indent:1}),D.push({label:"Facility/Rent",values:y,isExpense:!0,indent:1},{label:"Malpractice Insurance",values:w,isExpense:!0,indent:1},{label:"Commercial Insurance",values:h,isExpense:!0,indent:1},{label:"Marketing",values:U,isExpense:!0,indent:1},{label:"Dues, Boards & Subscriptions",values:T,isExpense:!0,indent:1},{label:"Payment Processing",values:j,isExpense:!0,indent:1},{label:"Internet & Utilities",values:R,isExpense:!0,indent:1},{label:"Software/EMR",values:H,isExpense:!0,indent:1},{label:"Accounting/Bookkeeping",values:G,isExpense:!0,indent:1},{label:"Printing & Supplies",values:ee,isExpense:!0,indent:1},{label:"Postage",values:z,isExpense:!0,indent:1},{label:"Travel & Meals",values:C,isExpense:!0,indent:1},{label:"Office Supplies",values:K,isExpense:!0,indent:1},{label:"Other Operating",values:Q,isExpense:!0,indent:1},{label:"Total SG&A",values:te,isSubtotal:!0,isExpense:!0},{label:"",values:[]},{label:"NET OPERATING INCOME",values:Z,isTotal:!0}),l){const P=i.map(ue=>ue.physicianTotalComp);D.push({label:"",values:[]},{label:"OWNER COMPENSATION",values:[],isSubtotal:!0},{label:"Net Profit (Take-Home)",values:P,isTotal:!0})}else{const P=i.map(Pe=>Pe.physicianBonus),ue=i.map(Pe=>Pe.physicianSalary),oe=i.map(Pe=>Pe.physicianTotalComp);D.push({label:"",values:[]},{label:"PHYSICIAN COMPENSATION",values:[],isSubtotal:!0},{label:"Base Salary",values:ue,indent:1},{label:"Performance Bonus",values:P,indent:1},{label:"Total Physician Comp",values:oe,isTotal:!0})}const fe=()=>{Is(t)};return e.jsxs(me,{className:"animate-slide-up",children:[e.jsxs(Ce,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsxs("div",{children:[e.jsx(Ae,{className:"text-lg",children:"3-Year Profit & Loss Statement"}),e.jsxs(ke,{children:["Detailed income statement projection for ",x.clientName]})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:fe,className:"gap-2",children:[e.jsx(Gt,{className:"h-4 w-4"}),"Export Excel"]})]}),e.jsx(le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(gt,{children:[e.jsx(ft,{children:e.jsxs(ae,{children:[e.jsx(Ne,{className:"w-[300px]",children:"Line Item"}),i.map(P=>e.jsxs(Ne,{className:"text-right min-w-[120px]",children:["Year ",P.year]},P.year))]})}),e.jsx(jt,{children:D.map((P,ue)=>P.label===""&&P.values.length===0?e.jsx(ae,{className:"h-4",children:e.jsx(I,{colSpan:i.length+1})},ue):P.values.length===0?e.jsx(ae,{className:"bg-muted/30",children:e.jsx(I,{colSpan:i.length+1,className:"font-bold text-sm",children:P.label})},ue):e.jsxs(ae,{className:de(P.isTotal&&"bg-primary/5 font-bold",P.isSubtotal&&"bg-muted/30 font-semibold"),children:[e.jsx(I,{className:de(P.indent&&`pl-${P.indent*4+4}`,P.isTotal&&"font-bold",P.isSubtotal&&"font-semibold"),style:{paddingLeft:P.indent?`${P.indent*16+16}px`:void 0},children:P.label}),P.values.map((oe,Pe)=>e.jsx(I,{className:de("text-right",P.isExpense&&"text-muted-foreground",P.isTotal&&(
16oe>=0?"text-success":"text-destructive"),P.isSubtotal&&"font-semibold"),children:P.isExpense&&oe>0?`(${A(oe)})`:A(oe)},Pe))]},ue))})]})})})]})}const ce={r:30,g:58,b:95},xe={r:201,g:162,b:39};function ni(t){return t==="pediatric"?{infant:"0-24 months",child:"2-6 years",adult:"7-17 years",adultLabel:"Youth",senior:"N/A",complex:"Complex/Special Needs",hideSenior:!0}:{infant:"Ages 0-2",child:"Ages 3-17",adult:"Ages 18-64",adultLabel:"Adult",senior:"Ages 65+",complex:"Complex",hideSenior:!1}}async function ii(t){try{const s=await(await fetch(t)).blob();return new Promise(i=>{const l=new FileReader;l.onloadend=()=>i(l.result),l.onerror=()=>i(null),l.readAsDataURL(s)})}catch{return null}}async function ri(t,x){const{assumptions:s,yearlySummaries:i,peakCapitalDeployment:l,breakEvenMonth:u}=t,r=new ks,d=await ii("/images/fh-logo.png"),M=r.internal.pageSize.getWidth(),b=r.internal.pageSize.getHeight(),c=20;let p=0;const E=()=>{r.addPage(),p=c,O()},g=G=>{p+G>b-30&&E()},O=()=>{r.setFillColor(ce.r,ce.g,ce.b),r.rect(0,0,M,15,"F"),r.setFillColor(xe.r,xe.g,xe.b),r.rect(0,15,M,2,"F"),r.setTextColor(255,255,255),r.setFontSize(10),r.setFont("helvetica","bold"),r.text("FREEDOM HEALTHWORKS",c,10),r.setFontSize(8),r.setFont("helvetica","normal");const G=r.internal.getNumberOfPages();r.text(`Page ${G}`,M-c-15,10)},v=G=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(G);if(r.setFillColor(ce.r,ce.g,ce.b),r.rect(0,0,M,b,"F"),d){const Z=(M-70)/2;r.addImage(d,"PNG",Z,30,70,25)}r.setFillColor(xe.r,xe.g,xe.b),r.rect(0,70,M,3,"F"),r.setTextColor(255,255,255),r.setFontSize(28),r.setFont("helvetica","bold"),r.text("FINANCIAL PROJECTION",M/2,100,{align:"center"}),r.text("& EXECUTIVE ANALYSIS",M/2,115,{align:"center"}),r.setFillColor(xe.r,xe.g,xe.b),r.rect(60,125,M-120,1,"F"),r.setFontSize(18),r.setFont("helvetica","normal"),r.text(s.clientName,M/2,150,{align:"center"}),r.setFontSize(12),r.text(`Prepared: ${new Date().toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"})}`,M/2,170,{align:"center"});const W=i[0],S=i[i.length-1],n=50,X=35,y=200,_=5,w=n*3+_*2,h=(M-w)/2;[{label:"Year 1 Revenue",value:v(W.totalRevenue)},{label:"Year 3 Revenue",value:v(S.totalRevenue)},{label:"Break-Even",value:u?`Month ${u}`:"N/A"}].forEach((G,te)=>{const Z=h+te*(n+_);r.setFillColor(xe.r,xe.g,xe.b),r.roundedRect(Z,y,n,X,3,3,"F"),r.setTextColor(ce.r,ce.g,ce.b),r.setFontSize(8),r.setFont("helvetica","normal"),r.text(G.label,Z+n/2,y+12,{align:"center"}),r.setFontSize(11),r.setFont("helvetica","bold"),r.text(G.value,Z+n/2,y+25,{align:"center"})}),r.setTextColor(255,255,255),r.setFontSize(10),r.setFont("helvetica","normal"),r.text("Prepared by Freedom Healthworks",M/2,b-30,{align:"center"}),r.setFontSize(8),r.text("www.freedomhealthworks.com",M/2,b-22,{align:"center"}),E(),p=25,r.setTextColor(ce.r,ce.g,ce.b),r.setFontSize(18),r.setFont("helvetica","bold"),r.text("Financial Summary",c,p),r.setFillColor(xe.r,xe.g,xe.b),r.rect(c,p+3,50,1.5,"F"),p+=15,r.setFontSize(12),r.setFont("helvetica","bold"),r.text("Key Assumptions",c,p),p+=8;const U=ni(s.practiceSpecialty);s.practiceSpecialty;const j=[["Starting Patients",String(s.patientsAtInception)],["Target Panel Size",String(s.maxPatientPanel)],[`Monthly Price (${U.adultLabel})`,v(s.adultPricePerMonth)],["Growth Rate (M1-6)",`${s.growthRateMonths1to6} patients/month`],["Growth Rate (M7-12)",`${s.growthRateMonths7to12} patients/month`],["Attrition Rate",`${s.attritionRate}%`]];ct(r,{startY:p,head:[],body:j,theme:"plain",styles:{fontSize:10,cellPadding:3},columnStyles:{0:{fontStyle:"bold",cellWidth:60},1:{cellWidth:50}},margin:{left:c}}),p=r.lastAutoTable.finalY+15,r.setFontSize(12),r.setFont("helvetica","bold"),r.text("Projected Performance",c,p),p+=8;const R=["Metric",...i.map(G=>`Year ${G.year}`)],H=[["Ending Patients",...i.map(G=>String(G.endingPatients))],["Total Revenue",...i.map(G=>v(G.totalRevenue))],["Cost of Services",...i.map(G=>v(G.totalCOS))],["SG&A Expenses",...i.map(G=>v(G.totalSGA))],["Net Income",...i.map(G=>v(G.netIncome))],["Physician Comp",...i.map(G=>v(G.physicianTotalComp))]];ct(r,{startY:p,head:[R],body:H,theme:"grid",headStyles:{fillColor:[ce.r,ce.g,ce.b],textColor:[255,255,255],fontStyle:"bold",fontSize:9},styles:{fontSize:9,cellPadding:4},columnStyles:{0:{fontStyle:"bold",cellWidth:45}},alternateRowStyles:{fillColor:[245,247,250]},margin:{left:c,right:c}}),p=r.lastAutoTable.finalY+15,g(60),r.setFontSize(12),r.setFont("helvetica","bold"),r.text("Key Performance Indicators",c,p),p+=8;const ee=[["Peak Capital Required",v(l||0)],["Break-Even Month",u?`Month ${u}`:"N/A"],["Year 3 Revenue Growth",`${((S.totalRevenue/W.totalRevenue-1)*100).toFixed(0)}%`],["Year 3 Physician Comp",v(S.physicianTotalComp)]];ct(r,{startY:p,head:[],body:ee,theme:"plain",styles:{fontSize:10,
16cellPadding:4},columnStyles:{0:{fontStyle:"bold",cellWidth:60},1:{fontStyle:"bold",textColor:[ce.r,ce.g,ce.b]}},margin:{left:c}}),E(),p=25,r.setTextColor(ce.r,ce.g,ce.b),r.setFontSize(18),r.setFont("helvetica","bold"),r.text("Executive Analysis",c,p),r.setFillColor(xe.r,xe.g,xe.b),r.rect(c,p+3,50,1.5,"F"),p+=15;const z=x.split(` 17`);for(const G of z){const te=G.trim();if(te===""){p+=3;continue}if(g(15),te.startsWith("## "))p+=5,r.setFontSize(13),r.setFont("helvetica","bold"),r.setTextColor(ce.r,ce.g,ce.b),r.text(te.replace("## ",""),c,p),r.setFillColor(xe.r,xe.g,xe.b),r.rect(c,p+2,40,.8,"F"),p+=10;else if(te.startsWith("### "))p+=3,r.setFontSize(11),r.setFont("helvetica","bold"),r.setTextColor(ce.r,ce.g,ce.b),r.text(te.replace("### ",""),c,p),p+=7;else if(te.startsWith("- ")||te.startsWith("* ")||/^\d+\.\s/.test(te)){r.setFontSize(10),r.setFont("helvetica","normal"),r.setTextColor(60,60,60);const m=te.replace(/^[-*]\s/,"").replace(/^\d+\.\s/,"").replace(/\*\*/g,"");r.setFillColor(xe.r,xe.g,xe.b),r.circle(c+2,p-1.5,1.2,"F"),r.splitTextToSize(m,M-c*2-10).forEach((L,D)=>{g(6),r.text(L,c+8,p),p+=5}),p+=1}else{r.setFontSize(10),r.setFont("helvetica","normal"),r.setTextColor(60,60,60);const Z=te.replace(/\*\*/g,"");r.splitTextToSize(Z,M-c*2).forEach(Y=>{g(6),r.text(Y,c,p),p+=5}),p+=2}}const C=r.internal.getNumberOfPages();for(let G=2;G<=C;G++)r.setPage(G),r.setDrawColor(ce.r,ce.g,ce.b),r.setLineWidth(.5),r.line(c,b-15,M-c,b-15),r.setFontSize(8),r.setTextColor(100,100,100),r.setFont("helvetica","normal"),r.text("Confidential - Prepared by Freedom Healthworks",c,b-10),r.text(`Generated ${new Date().toLocaleDateString()}`,M-c,b-10,{align:"right"});const K=s.clientName.replace(/[^a-zA-Z0-9]/g,"_").substring(0,30),Q=new Date().toISOString().split("T")[0];r.save(`${K}_Executive_Report_${Q}.pdf`)}function li({results:t}){const[x,s]=F.useState(null),[i,l]=F.useState(!1),[u,r]=F.useState(!1),d=async()=>{var c,p,E;l(!0),s("");try{const g=`${pa}/functions/v1/generate-analysis`,O=await fetch(g,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${na}`},body:JSON.stringify({projectionData:t})});if(!O.ok){if(O.status===429)throw new Error("Rate limit exceeded. Please try again shortly.");if(O.status===402)throw new Error("AI credits exhausted. Please add credits.");const y=await O.json().catch(()=>({}));throw new Error(y.error||`Analysis failed (${O.status})`)}if(!O.body)throw new Error("No response body");const v=O.body.getReader(),W=new TextDecoder;let S="",n="",X=!1;for(;!X;){const{done:y,value:_}=await v.read();if(y)break;S+=W.decode(_,{stream:!0});let w;for(;(w=S.indexOf(` 18`))!==-1;){let h=S.slice(0,w);if(S=S.slice(w+1),h.endsWith("\r")&&(h=h.slice(0,-1)),h.startsWith(":")||h.trim()===""||!h.startsWith("data: "))continue;const T=h.slice(6).trim();if(T==="[DONE]"){X=!0;break}try{const j=(E=(p=(c=JSON.parse(T).choices)==null?void 0:c[0])==null?void 0:p.delta)==null?void 0:E.content;j&&(n+=j,s(n))}catch{S=h+` 19`+S;break}}}if(l(!1),n)ge.success("Executive analysis generated");
19else throw new Error("No analysis content received")}catch(g){console.error("Error generating analysis:",g);const O=g instanceof Error?g.message:"Failed to generate analysis";ge.error(O),x||s(null),l(!1)}},M=async()=>{if(!x){ge.error("Please generate analysis first");return}r(!0);try{await ri(t,x),ge.success("Report downloaded")}catch(c){console.error("Error generating PDF:",c),ge.error("Failed to generate PDF report")}finally{r(!1)}},b=c=>{const E=c.replace(/\*\*\*/g,"").replace(/\*\*/g,"").replace(/\*/g,"").split(` 20`),g=[];let O=[];const v=()=>{O.length>0&&(g.push(e.jsx("ul",{className:"list-disc pl-6 space-y-1.5 mb-4",children:O.map((W,S)=>e.jsx("li",{className:"text-muted-foreground leading-relaxed",children:W},S))},`list-${g.length}`)),O=[])};return E.forEach((W,S)=>{const n=W.trim();if(n.startsWith("## "))v(),g.push(e.jsx("h2",{className:"text-xl font-bold text-foreground mt-6 mb-3 border-b border-border pb-2",children:n.replace("## ","")},S));else if(n.startsWith("### "))v(),g.push(e.jsx("h3",{className:"text-lg font-semibold text-foreground mt-4 mb-2",children:n.replace("### ","")},S));else if(n.startsWith("# "))v(),g.push(e.jsx("h1",{className:"text-2xl font-bold text-foreground mt-6 mb-4",children:n.replace("# ","")},S));else if(n.startsWith("- ")||n.startsWith("⢠")||/^\d+\.\s/.test(n)){const X=n.replace(/^[-â¢]\s/,"").replace(/^\d+\.\s/,"");O.push(X)}else n===""?v():(v(),g.push(e.jsx("p",{className:"text-muted-foreground mb-3 leading-relaxed",children:n},S)))}),v(),g};return e.jsxs(me,{className:"animate-slide-up",children:[e.jsx(Ce,{className:"bg-gradient-primary text-primary-foreground rounded-t-lg",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-background/20",children:e.jsx(Ve,{className:"h-5 w-5 text-primary-foreground"})}),e.jsxs("div",{children:[e.jsx(Ae,{className:"text-primary-foreground",children:"Executive Analysis"}),e.jsx(ke,{className:"text-primary-foreground/70",children:"AI-powered CEO-level insights and recommendations"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:x&&e.jsxs(e.Fragment,{children:[e.jsxs(V,{variant:"outline",size:"sm",onClick:d,disabled:i,className:"gap-2 bg-background/10 border-background/20 text-primary-foreground hover:bg-background/20",children:[e.jsx(xs,{className:de("h-4 w-4",i&&"animate-spin")}),"Regenerate"]}),e.jsxs(V,{size:"sm",onClick:M,disabled:u,className:"gap-2 bg-accent text-accent-foreground hover:bg-accent/90",children:[u?e.jsx(nt,{className:"h-4 w-4 animate-spin"}):e.jsx(Sa,{className:"h-4 w-4"}),"Download Report"]})]})})]})}),e.jsxs(le,{className:"pt-6",children:[!x&&!i&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"inline-flex items-center justify-center p-4 rounded-full bg-primary/10 mb-4",children:e.jsx(xa,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Generate Executive Analysis"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md mx-auto",children:"Get AI-powered CEO-level insights, strategic recommendations, and a 90-day action plan based on your projections."}),e.jsxs(V,{onClick:d,className:"gap-2",children:[e.jsx(Ve,{className:"h-4 w-4"}),"Generate Analysis"]})]}),i&&!x&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(nt,{className:"h-8 w-8 animate-spin text-primary mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Generating executive analysis..."}),e.jsx("p",{className:"text-sm text-muted-foreground/60 mt-1",children:"This may take a moment"})]}),x&&e.jsxs("div",{className:"prose prose-slate max-w-none",children:[b(x),i&&e.jsxs("div",{className:"flex items-center gap-2 mt-4 text-muted-foreground",children:[e.jsx(nt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Writing..."})]})]})]})]})}const tt=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"];function rs({assumptions:t,totalPatients:x,year:s}){const i=bs(t.practiceSpecialty),l=t.practiceSpecialty==="pediatric",u=t.pricingMode||"four_tier";let r=[];u==="flat"?r=[{name:"All Members",price:t.flatPricePerMonth||0,weight:1,color:tt[0]}]:u==="two_tier"||u==="custom"?r=(t.customTiers||[]).map((b,c)=>({name:b.label||`Tier ${c+1}`,price:b.pricePerMonth||0,weight:b.weighting||0,color:tt[c%tt.length]})):r=[{name:`Infant (${i.infant})`,price:t.infantPricePerMonth||0,weight:t.infantWeighting||0,color:tt[0]},{name:`Child (${i.child})`,price:t.childPricePerMonth||0,weight:t.childWeighting||0,color:tt[1]},{name:l?`Youth (${i.adult})`:`Adult (${i.adult})`,price:t.adultPricePerMonth||0,weight:t.adultWeighting||0,color:tt[2]},{name:`Senior (${i.senior})`,price:t.seniorPricePerMonth||0,weight:t.seniorWeighting||0,color:tt[3],hideForPediatric:!0}].filter(c=>!l||!("hideForPediatric"in c&&c.hideForPediatric));const d=r.filter(b=>b.weight>0).map(b=>{const c=Math.round(x*b.weight),p=c*b.price,E=p*12;return{name:b.name,patients:c,monthlyRevenue:p,annualRevenue:E,price:b.price,weight:b.weight,color:b.color}}),M=d.reduce((b,c)=>b+c.annualRevenue,0);return e.jsxs(me,{className:"animate-slide-up",children:[e.jsxs(Ce,{children:[e.jsxs(Ae,{className:"text-lg",children:["Year ",s," Revenue by Age Tier"]}),e.jsxs(ke,{children:["Membership revenue breakdown: ",A(M),"/year"]})]}),e.jsx(le,{children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(Cn,{children:[e.jsx(kn,{data:d,dataKey:"annualRevenue",nameKey:"name",cx:"50%",cy:"50%",outerRadius:80,label:({name:b,percent:c}
20)=>`${b}: ${(c*100).toFixed(0)}%`,labelLine:!1,children:d.map((b,c)=>e.jsx(ws,{fill:b.color},`cell-${c}`))}),e.jsx(De,{formatter:b=>A(b),contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}})]})})}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-xs font-medium text-muted-foreground pb-2 border-b",children:[e.jsx("span",{children:"Age Tier"}),e.jsx("span",{className:"text-right",children:"Patients"}),e.jsx("span",{className:"text-right",children:"$/Month"}),e.jsx("span",{className:"text-right",children:"Annual Rev"})]}),d.map(b=>e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-sm py-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:b.color}}),e.jsx("span",{className:"truncate",children:b.name})]}),e.jsx("span",{className:"text-right",children:b.patients}),e.jsxs("span",{className:"text-right",children:["$",b.price]}),e.jsx("span",{className:"text-right font-medium",children:A(b.annualRevenue)})]},b.name)),e.jsxs("div",{className:"grid grid-cols-4 gap-2 text-sm font-semibold pt-2 border-t",children:[e.jsx("span",{children:"Total"}),e.jsx("span",{className:"text-right",children:x}),e.jsx("span",{className:"text-right",children:"-"}),e.jsx("span",{className:"text-right text-primary",children:A(M)})]})]})]})})]})}function oi({assumptions:t}){const[x,s]=F.useState(!0),i=mt(t),l=t.pricingMode||"four_tier",u=t.tbdFields||[],r=l==="flat"?`Flat ${A(t.flatPricePerMonth||0)}/mo`:l==="two_tier"?(t.customTiers||[]).map(c=>`${c.label}: ${A(c.pricePerMonth)} (${Math.round((c.weighting||0)*100)}%)`).join(" · "):[t.infantWeighting>0&&`Infant ${A(t.infantPricePerMonth)} (${Math.round(t.infantWeighting*100)}%)`,t.childWeighting>0&&`Child ${A(t.childPricePerMonth)} (${Math.round(t.childWeighting*100)}%)`,t.adultWeighting>0&&`Adult ${A(t.adultPricePerMonth)} (${Math.round(t.adultWeighting*100)}%)`,t.seniorWeighting>0&&`Senior ${A(t.seniorPricePerMonth)} (${Math.round(t.seniorWeighting*100)}%)`].filter(Boolean).join(" · "),d=t.softwareRampPrice!==void 0?`${A(t.softwareRampPrice)}/mo ramp â ${A(t.softwareEmrMonthly)}/mo (after ${t.softwareRampUntilPatients??"?"} patients or month ${t.softwareRampMaxMonths??"?"})`:`${A(t.softwareEmrMonthly||0)}/mo`,M=[["Opening date",new Date(t.startupDate).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"})],["Projection length",`${t.projectionYears} years`],["Pricing",r||"â"],["Blended price",`${A(i)}/mo`],["Lease",`${A(t.rent||0)}/mo`,"rent"],["Malpractice",`${A(t.malpracticeInsurance||0)}/yr`,"malpracticeInsurance"],["Software / EMR",d,"softwareEmrMonthly"],["Staff wages",t.staffWagesMonthly?`${A(t.staffWagesMonthly)}/mo after ${t.staffStartAtPatients} patients`:"â","staffWagesMonthly"],["Growth (M1-6 â M7-12 â Y2+)",`${t.growthRateMonths1to6}/mo â ${t.growthRateMonths7to12}/mo â ${t.growthRateYear2Plus}/mo`],["Max panel",t.enableMaxPanel?`${t.maxPatientPanel} patients`:"Uncapped"]];return e.jsxs(me,{children:[e.jsxs("button",{type:"button",onClick:()=>s(!x),className:"w-full flex items-center justify-between p-4 hover:bg-muted/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:"Assumptions driving these numbers"}),u.length>0&&e.jsxs(pe,{variant:"outline",className:"border-warning text-warning bg-warning/5",children:[u.length," estimate",u.length===1?"":"s"," needed"]})]}),x?e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(qs,{className:"h-4 w-4 text-muted-foreground"})]}),x&&e.jsxs(le,{className:"pt-0 pb-4",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:M.map(([b,c,p])=>{const E=p&&u.includes(p);return e.jsxs("div",{className:"flex items-start justify-between gap-3 py-1.5 border-b border-border/40 last:border-0",children:[e.jsx("span",{className:"text-muted-foreground",children:b}),e.jsxs("span",{className:de("text-right font-medium",E&&"text-warning"),children:[c,E&&e.jsx(pe,{variant:"outline",className:"ml-2 text-[10px] border-warning text-warning bg-warning/5",children:"TBD"})]})]},b)})}),t.scenarioNotes&&e.jsxs("div",{className:"mt-4 p-3 rounded-md bg-muted/40 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Notes: "}),t.scenarioNotes]}),u.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground italic",children:["Fields marked ",e.jsx("span",{className:"text-warning font-medium",children:"TBD"})," are placeholder values â confirm with the client before sharing."]})]})]})}const ci={malpracticeInsurance:"Malpractice insurance",staffWagesMonthly:"Staff wages",rent:"Lease",commercialInsurance:"Commercial insurance",softwareEmrMonthly:"EMR / software"};function di({assumptions:t,results:x}){const s=[],i=t.tbdFields||[];
20i.forEach(r=>s.push(`${ci[r]||r} is a placeholder â confirm with client.`)),!i.includes("malpracticeInsurance")&&(!t.malpracticeInsurance||t.malpracticeInsurance===0)&&s.push("Malpractice insurance is $0 â every practice carries this expense.");const l=new Date(t.startupDate);!isNaN(l.getTime())&&l<new Date&&s.push(`Opening date (${l.toLocaleDateString()}) is in the past.`);const u=x.yearlySummaries[x.yearlySummaries.length-1];if(u){const r=(u.totalCOS||0)+(u.totalSGA||0),M=mt(t)*12*(t.maxPatientPanel||500);r>M&&M>0&&s.push(`Even at max panel, blended revenue (${A(M)}) cannot cover Year ${x.yearlySummaries.length} expenses (${A(r)}).`)}return s.length===0?null:e.jsxs(Rn,{variant:"default",className:"border-warning bg-warning/5",children:[e.jsx(Ks,{className:"h-4 w-4 text-warning"}),e.jsxs($n,{className:"text-warning",children:[s.length," item",s.length===1?"":"s"," to confirm before sharing"]}),e.jsx(An,{children:e.jsx("ul",{className:"list-disc pl-5 mt-2 space-y-1 text-sm",children:s.map((r,d)=>e.jsx("li",{children:r},d))})})]})}const $t={infant:"hsl(var(--chart-1))",child:"hsl(var(--chart-2))",adult:"hsl(var(--chart-3))",senior:"hsl(var(--chart-4))"};function mi({monthlyProjections:t,assumptions:x}){var E;const s=t.map((g,O)=>{const v=g.patientGrowth,W=Math.round(v*(x.infantWeighting||0)),S=Math.round(v*(x.childWeighting||0)),n=Math.round(v*(x.adultWeighting||0)),X=Math.round(v*(x.seniorWeighting||0)),y=Math.pow(1+(x.expenseGrowthRate||3)/100,g.year-1);let _=y;g.year>=4&&(_=y*(1+(x.marketingDeclineYear4||-75)/100));const w=x.marketing/12*_,h=v>0?w/v:0;return{month:g.date,monthNum:g.month,year:g.year,totalGrowth:v,infantGrowth:W,childGrowth:S,adultGrowth:n,seniorGrowth:X,marketing:w,cac:h,cumulative:g.endingPatients,attrition:g.attrition}}),i=s.reduce((g,O)=>g+O.totalGrowth,0),l=s.reduce((g,O)=>g+O.marketing,0),u=i>0?l/i:0,r=s.filter(g=>g.year===1).reduce((g,O)=>g+O.totalGrowth,0),d=bs(x.practiceSpecialty),M=x.practiceSpecialty==="pediatric",c=[{key:"infantGrowth",name:`Infant (${d.infant})`,color:$t.infant,weight:x.infantWeighting||0},{key:"childGrowth",name:`Child (${d.child})`,color:$t.child,weight:x.childWeighting||0},{key:"adultGrowth",name:M?`Youth (${d.adult})`:`Adult (${d.adult})`,color:$t.adult,weight:x.adultWeighting||0},{key:"seniorGrowth",name:`Senior (${d.senior})`,color:$t.senior,weight:x.seniorWeighting||0,hideForPediatric:!0}].filter(g=>g.weight>0).filter(g=>!M||!("hideForPediatric"in g&&g.hideForPediatric)),p=({active:g,payload:O,label:v})=>{var W;if(g&&O&&O.length){const S=(W=O[0])==null?void 0:W.payload;return e.jsxs("div",{className:"bg-card border rounded-lg p-3 shadow-lg",children:[e.jsxs("p",{className:"font-medium text-sm mb-2",children:[v," (Year ",S==null?void 0:S.year,")"]}),e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"New Patients:"}),e.jsxs("span",{className:"font-medium",children:["+",S==null?void 0:S.totalGrowth]})]}),c.map(n=>{const X=S==null?void 0:S[n.key];return X>0?e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsxs("span",{style:{color:n.color},children:[n.name,":"]}),e.jsxs("span",{children:["+",X]})]},n.key):null}),e.jsx("hr",{className:"my-1 border-border"}),e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"Attrition:"}),e.jsxs("span",{className:"text-destructive",children:["-",S==null?void 0:S.attrition]})]}),e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"Marketing:"}),e.jsx("span",{children:A(S==null?void 0:S.marketing)})]}),e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"CAC:"}),e.jsx("span",{className:"font-medium",children:(S==null?void 0:S.cac)>0?A(S==null?void 0:S.cac):"N/A"})]}),e.jsx("hr",{className:"my-1 border-border"}),e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsx("span",{className:"text-muted-foreground",children:"Total Panel:"}),e.jsx("span",{className:"font-semibold",children:S==null?void 0:S.cumulative})]})]})]})}return null};return e.jsxs(me,{className:"animate-slide-up",children:[e.jsx(Ce,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-5 w-5 text-primary"}),"Patient Acquisition Timeline"]}),e.jsx(ke,{children:"Monthly growth by age tier with marketing spend correlation"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(pe,{variant:"outline",className:"gap-1",children:[e.jsx(Qe,{className:"h-3 w-3"}),i," total acquired"]}),e.jsxs(pe,{variant:"outline",className:"gap-1",children:[e.jsx(_t,{className:"h-3 w-3"}),A(u)," avg CAC"]})]})]})}),e.jsxs(le,{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Year 1 Growth"}),e.jsxs("p",{className:"text-xl font-bold",children:["+",r]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"new patients"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Marketing"}),e.jsx("p",{className:"text-xl font-bold",children:A(l)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[x.projectionYears,"-year total"]})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg CAC"}),e.jsx("p",{className:"text-xl font-bold",children:A(u)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"per patient"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 border",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Final Panel"}),e.jsx("p",{className:"text-xl font-bold",children:((E=s[s.length-1])==null?void 0:E.
20cumulative)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"patients"})]})]}),e.jsx("div",{className:"h-[400px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(Ps,{data:s,margin:{top:20,right:30,left:20,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Ye,{dataKey:"month",tick:{fontSize:10},interval:Math.floor(s.length/12)}),e.jsx(Oe,{yAxisId:"left",tick:{fontSize:10},label:{value:"New Patients",angle:-90,position:"insideLeft",fontSize:11}}),e.jsx(Oe,{yAxisId:"right",orientation:"right",tick:{fontSize:10},tickFormatter:g=>`$${(g/1e3).toFixed(0)}k`,label:{value:"Marketing ($)",angle:90,position:"insideRight",fontSize:11}}),e.jsx(De,{content:e.jsx(p,{})}),e.jsx(Ge,{}),c.map((g,O)=>e.jsx(be,{yAxisId:"left",dataKey:g.key,name:g.name,stackId:"growth",fill:g.color,radius:O===c.length-1?[4,4,0,0]:[0,0,0,0]},g.key)),e.jsx(Ze,{yAxisId:"right",type:"monotone",dataKey:"marketing",name:"Marketing Spend",stroke:"hsl(var(--primary))",strokeWidth:2,dot:!1})]})})}),e.jsx("div",{className:"flex flex-wrap justify-center gap-4 pt-2 border-t",children:c.map(g=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("div",{className:"w-3 h-3 rounded-sm",style:{backgroundColor:g.color}}),e.jsx("span",{children:g.name}),e.jsxs("span",{className:"text-muted-foreground",children:["(",(g.weight*100).toFixed(0),"%)"]})]},g.key))})]})]})}const st=["hsl(var(--chart-1))","hsl(var(--chart-2))","hsl(var(--chart-3))","hsl(var(--chart-4))","hsl(var(--chart-5))"],ls=[{id:"conservative",name:"Conservative",color:st[0],growthM1_6:10,growthM7_12:8,growthY2Plus:8,marketing:36e3},{id:"moderate",name:"Moderate",color:st[1],growthM1_6:15,growthM7_12:12,growthY2Plus:12,marketing:48e3},{id:"aggressive",name:"Aggressive",color:st[2],growthM1_6:25,growthM7_12:20,growthY2Plus:18,marketing:72e3}];function hi({baseAssumptions:t}){const{user:x}=ga(),[s,i]=F.useState(ls),[l,u]=F.useState("patients"),[r,d]=F.useState([]),[M,b]=F.useState([]),[c,p]=F.useState(!1),[E,g]=F.useState(!1),[O,v]=F.useState(""),[W,S]=F.useState(""),[n,X]=F.useState(!1),[y,_]=F.useState(!1),[w,h]=F.useState("mine");F.useEffect(()=>{x&&(T(),U())},[x]);const T=async()=>{if(x){_(!0);try{const{data:m,error:Y}=await at.from("saved_scenarios").select("*").eq("user_id",x.id).order("updated_at",{ascending:!1});if(Y)throw Y;d((m||[]).map(L=>({...L,scenarios:L.scenarios||[]})))}catch(m){console.error("Error fetching saved scenarios:",m)}finally{_(!1)}}},U=async()=>{if(x)try{const{data:m,error:Y}=await at.from("saved_scenarios").select("*").eq("is_shared",!0).neq("user_id",x.id).order("updated_at",{ascending:!1});if(Y)throw Y;b((m||[]).map(L=>({...L,scenarios:L.scenarios||[]})))}catch(m){console.error("Error fetching shared scenarios:",m)}},j=async(m,Y)=>{if(x)try{const{data:L}=await at.from("profiles").select("full_name, email").eq("user_id",x.id).maybeSingle(),D=(L==null?void 0:L.full_name)||(L==null?void 0:L.email)||"Team Member",{error:se}=await at.from("saved_scenarios").update({is_shared:!Y,shared_by_name:Y?null:D}).eq("id",m).eq("user_id",x.id);if(se)throw se;ge.success(Y?"Scenario set is now private":"Scenario set shared with team"),T()}catch(L){console.error("Error toggling share:",L),ge.error("Failed to update sharing settings")}},R=async()=>{if(!x||!O.trim()){ge.error("Please enter a name for this scenario set");return}X(!0);try{const{error:m}=await at.from("saved_scenarios").insert([{user_id:x.id,name:O.trim(),description:W.trim()||null,scenarios:JSON.parse(JSON.stringify(s))}]);if(m)throw m;ge.success("Scenarios saved successfully"),p(!1),v(""),S(""),T()}catch(m){console.error("Error saving scenarios:",m),ge.error("Failed to save scenarios")}finally{X(!1)}},H=m=>{const Y=m.scenarios.map((L,D)=>({...L,color:L.color||st[D%st.length]}));i(Y),g(!1),ge.success(`Loaded "${m.name}"`)},ee=async(m,Y)=>{Y.stopPropagation();try{const{error:L}=await at.from("saved_scenarios").delete().eq("id",m);if(L)throw L;ge.success("Scenario set deleted"),T()}catch(L){console.error("Error deleting scenarios:",L),ge.error("Failed to delete scenario set")}},z=F.useMemo(()=>s.map(m=>{const Y={...t,growthRateMonths1to6:m.growthM1_6,growthRateMonths7to12:m.growthM7_12,growthRateYear2Plus:m.growthY2Plus,marketing:m.marketing},L=yt(Y),D=mt(Y),se=L.yearlySummaries[0],fe=L.yearlySummaries[L.yearlySummaries.length-1],P=L.monthlyProjections.reduce((Ee,it)=>Ee+it.patientGrowth,0),ue=m.marketing*t.projectionYears,oe=P>0?ue/P:0,Pe=D*(t.attritionRate>0?1/(t.attritionRate/100):60);return{scenario:m,results:L,metrics:{year1Patients:se.endingPatients,year3Patients:fe.endingPatients,year1Revenue:se.totalRevenue,year3Revenue:fe.totalRevenue,year1NetIncome:se.netIncome,year3NetIncome:fe.netIncome,totalNewPatients:P,avgCAC:oe,ltv:Pe,ltvCacRatio:oe>0?Pe/oe:0,breakEvenMonth:L.breakEvenMonth,peakCapital:L.peakCapitalDeployment},monthlyData:L.monthlyProjections.map(Ee=>({month:Ee.date,patients:Ee.endingPatients,revenue:Ee.totalRevenue}))}}),[s,t]),C=F.useMemo(()=>{var Y;return(((Y=z[0])==null?void 0:Y.monthlyData)||[]).map((L,D)=>{var fe,P;const se={month:(P=(fe=z[0])==null?void 0:fe.monthlyData[D])==null?void 0:P.month};return z.forEach(ue=>{const oe=ue.monthlyData[D];se[`${ue.scenario.id}_patients`]=(oe==null?void 0:oe.patients)||0,se[`${ue.scenario.id}_revenue`]=(oe==null?void 0:oe.revenue)||0}),se})},[z]),K=()=>
20{if(s.length>=5)return;const m=`custom_${Date.now()}`;i([...s,{id:m,name:`Custom ${s.length+1}`,color:st[s.length%st.length],growthM1_6:15,growthM7_12:12,growthY2Plus:10,marketing:48e3}])},Q=m=>{s.length<=1||i(s.filter(Y=>Y.id!==m))},G=(m,Y,L)=>{i(s.map(D=>D.id===m?{...D,[Y]:L}:D))},te=()=>{i(ls)},Z=({active:m,payload:Y,label:L})=>m&&Y&&Y.length?e.jsxs("div",{className:"bg-card border rounded-lg p-3 shadow-lg",children:[e.jsx("p",{className:"font-medium text-sm mb-2",children:L}),e.jsx("div",{className:"space-y-1 text-xs",children:Y.map((D,se)=>{const fe=D.dataKey.split("_")[0],P=s.find(oe=>oe.id===fe),ue=D.dataKey.split("_")[1];return e.jsxs("p",{className:"flex justify-between gap-4",children:[e.jsxs("span",{style:{color:D.color},children:[P==null?void 0:P.name,":"]}),e.jsx("span",{className:"font-medium",children:ue==="revenue"?A(D.value):D.value})]},se)})})]}):null;return e.jsxs(me,{className:"animate-slide-up",children:[e.jsx(Ce,{children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(Ae,{className:"flex items-center gap-2",children:[e.jsx(Je,{className:"h-5 w-5 text-primary"}),"Growth Scenario Builder"]}),e.jsx(ke,{children:"Compare different growth strategies and their financial impact"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[x&&e.jsxs(e.Fragment,{children:[e.jsxs(ra,{open:E,onOpenChange:g,children:[e.jsx(Ka,{asChild:!0,children:e.jsxs(V,{variant:"outline",size:"sm",children:[e.jsx(zt,{className:"h-4 w-4 mr-1"}),"Load"]}
20)}),e.jsxs(la,{className:"max-w-md",children:[e.jsxs(oa,{children:[e.jsx(ca,{children:"Load Scenarios"}),e.jsx(da,{children:"Load your saved scenarios or team-shared scenarios"})]}),e.jsxs("div",{className:"flex gap-2 border-b",children:[e.jsxs("button",{className:`px-3 py-2 text-sm font-medium border-b-2 transition-colors ${w==="mine"?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>h("mine"),children:[e.jsx(En,{className:"h-3 w-3 inline mr-1"}),"My Scenarios (",r.length,")"]}),e.jsxs("button",{className:`px-3 py-2 text-sm font-medium border-b-2 transition-colors ${w==="shared"?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,onClick:()=>h("shared"),children:[e.jsx(ea,{className:"h-3 w-3 inline mr-1"}),"Shared (",M.length,")"]})]}),e.jsx(fa,{className:"max-h-[300px]",children:w==="mine"?r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No saved scenarios yet"}):e.jsx("div",{className:"space-y-2",children:r.map(m=>e.jsx("div",{className:"p-3 rounded-lg border hover:bg-muted/50 cursor-pointer group",onClick:()=>H(m),children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:m.name}),m.is_shared&&e.jsxs(pe,{variant:"secondary",className:"text-xs",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Shared"]})]}),m.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:m.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.scenarios.length," scenarios ⢠",new Date(m.updated_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(V,{variant:"ghost",size:"icon",className:"h-7 w-7",title:m.is_shared?"Make private":"Share with team",onClick:Y=>{Y.stopPropagation(),j(m.id,m.is_shared)},children:m.is_shared?e.jsx(ea,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(In,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx(V,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:Y=>ee(m.id,Y),children:e.jsx(ja,{className:"h-3.5 w-3.5 text-destructive"})})]})]})},m.id))}):M.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No shared scenarios from team members"}):e.jsx("div",{className:"space-y-2",children:M.map(m=>e.jsxs("div",{className:"p-3 rounded-lg border hover:bg-muted/50 cursor-pointer",onClick:()=>H(m),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm",children:m.name}),e.jsxs(pe,{variant:"outline",className:"text-xs",children:[e.jsx(Qe,{className:"h-3 w-3 mr-1"}),m.shared_by_name||"Team"]})]}),m.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:m.description}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.scenarios.length," scenarios ⢠",new Date(m.updated_at).toLocaleDateString()]})]},m.id))})})]})]}),e.jsxs(ra,{open:c,onOpenChange:p,children:[e.jsx(Ka,{asChild:!0,children:e.jsxs(V,{variant:"outline",size:"sm",children:[e.jsx(ha,{className:"h-4 w-4 mr-1"}),"Save"]})}),e.jsxs(la,{children:[e.jsxs(oa,{children:[e.jsx(ca,{children:"Save Scenario Set"}),e.jsx(da,{children:"Save your current scenarios for future reference"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"saveName",children:"Name"}),e.jsx(Me,{id:"saveName",value:O,onChange:m=>v(m.target.value),placeholder:"e.g., Q1 2025 Growth Analysis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"saveDesc",children:"Description (optional)"}),e.jsx(Me,{id:"saveDesc",value:W,onChange:m=>S(m.target.value),placeholder:"Brief description..."})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Scenarios to save:"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:s.map(m=>e.jsx(pe,{variant:"secondary",className:"text-xs",children:m.name},m.id))})]})]}),e.jsxs(ps,{children:[e.jsx(V,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx(V,{onClick:R,disabled:n||!O.trim(),children:n?"Saving...":"Save"})]})]})]})]}),e.jsxs(V,{variant:"outline",size:"sm",onClick:te,children:[e.jsx(xs,{className:"h-4 w-4 mr-1"}),"Reset"]}),e.jsxs(V,{size:"sm",onClick:K,disabled:s.length>=5,children:[e.jsx(gs,{className:"h-4 w-4 mr-1"}),"Add Scenario"]})]})]})}),e.jsxs(le,{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(m=>e.jsxs("div",{className:"p-4 rounded-lg border-2 space-y-4",style:{borderColor:m.color},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Me,{value:m.name,onChange:Y=>G(m.id,"name",Y.target.value),className:"font-medium text-sm h-8 w-32"}),s.length>1&&e.jsx(V,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Q(m.id),children:e.jsx(ya,{className:"h-4 w-4 text-muted-foreground"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx(Se,{children:"Growth M1-6"}),e.jsxs("span",{className:"font-medium",children:[m.growthM1_6,"/mo"]})]}),e.jsx(ut,{value:[m.growthM1_6],onValueChange:([Y])=>G(m.id,"growthM1_6",Y),min:5,max:40,step:1,className:"w-full"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx(Se,{children:"Growth M7-12"}),e.jsxs("span",{className:"font-medium",children:[m.growthM7_12,"/mo"]})]}),e.jsx(ut,{value:[m.growthM7_12],onValueChange:([Y])=>G(m.id,"growthM7_12",Y),min:5,max:35,step:1,className:"w-full"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx(Se,{children:"Growth Y2+"}),e.jsxs("span",{className:"font-medium",children:[m.growthY2Plus,"/mo"]})]}),e.jsx(ut,{value:[m.growthY2Plus],onValueChange:([Y])=>G(m.id,"growthY2Plus",Y),min:5,max:30,step:1,className:"w-full"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx(Se,{children:"Annual Marketing"}),e.jsx("span",{className:"font-medium",children:A(m.marketing)})]}),e.jsx(ut,{value:[m.marketing],onValueChange:([Y])=>G(m.id,"marketing",Y),min:12e3,max:12e4,step:6e3,className:"w-full"})]})]})]},m.id))}),e.jsxs("div",{className:"flex justify-center gap-2",children:[e.jsxs(V,{variant:l==="patients"?"default":"outline",size:"sm",onClick:()=>u("patients"),children:[e.jsx(Qe,{className:"h-4 w-4 mr-1"}),"Patients"]}),e.jsxs(V,{variant:l==="revenue"?"default":"outline",size:"sm",onClick:()=>u("revenue"),children:[e.jsx(_t,{className:"h-4 w-4 mr-1"}),"Revenue"]}),e.jsxs(V,{variant:l==="cac"?"default":"outline",size:"sm",onClick:()=>u("cac"),children:[e.jsx(fs,{className:"h-4 w-4 mr-1"}),"CAC & LTV"]})]}),l!=="cac"&&e.jsx("div",{className:"h-[300px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(Ms,{data:C,margin:{top:20,right:30,left:2
200,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Ye,{dataKey:"month",tick:{fontSize:10},interval:Math.floor(C.length/12)}),e.jsx(Oe,{tick:{fontSize:10},tickFormatter:m=>l==="revenue"?`$${(m/1e3).toFixed(0)}k`:m.toString()}),e.jsx(De,{content:e.jsx(Z,{})}),e.jsx(Ge,{}),s.map(m=>e.jsx(Ze,{type:"monotone",dataKey:`${m.id}_${l}`,name:m.name,stroke:m.color,strokeWidth:2,dot:!1},m.id))]})})}),l==="cac"&&e.jsx("div",{className:"h-[300px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(ot,{data:z.map(m=>({name:m.scenario.name,cac:m.metrics.avgCAC,ltv:m.metrics.ltv,ratio:m.metrics.ltvCacRatio,color:m.scenario.color})),margin:{top:20,right:30,left:20,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Ye,{dataKey:"name",tick:{fontSize:11}}),e.jsx(Oe,{tick:{fontSize:10},tickFormatter:m=>`$${m.toLocaleString()}`}),e.jsx(De,{formatter:(m,Y)=>[Y==="ratio"?`${m.toFixed(1)}x`:A(m),Y==="cac"?"CAC":Y==="ltv"?"LTV":"LTV:CAC"],contentStyle:{backgroundColor:"hsl(var(--card))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),e.jsx(Ge,{}),e.jsx(be,{dataKey:"cac",name:"CAC",fill:"hsl(var(--destructive))"}),e.jsx(be,{dataKey:"ltv",name:"LTV",fill:"hsl(var(--primary))"})]})})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-2 px-3 font-medium",children:"Metric"}),s.map(m=>e.jsx("th",{className:"text-right py-2 px-3 font-medium",style:{color:m.color},children:m.name},m.id))]})}),e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Year 1 Patients"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:m.metrics.year1Patients},m.scenario.id))]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Year 3 Patients"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:m.metrics.year3Patients},m.scenario.id))]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Year 1 Revenue"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:A(m.metrics.year1Revenue)},m.scenario.id))]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Year 3 Revenue"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:A(m.metrics.year3Revenue)},m.scenario.id))]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Avg CAC"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:A(m.metrics.avgCAC)},m.scenario.id))]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"LTV:CAC Ratio"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3",children:e.jsxs(pe,{variant:m.metrics.ltvCacRatio>=3?"default":m.metrics.ltvCacRatio>=2?"secondary":"destructive",children:[m.metrics.ltvCacRatio.toFixed(1),"x"]})},m.scenario.id))]}),e.jsxs("tr",{className:"border-b",children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Break-Even Month"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:m.metrics.breakEvenMonth?`Month ${m.metrics.breakEvenMonth}`:"N/A"},m.scenario.id))]}),e.jsxs("tr",{children:[e.jsx("td",{className:"py-2 px-3 text-muted-foreground",children:"Peak Capital"}),z.map(m=>e.jsx("td",{className:"text-right py-2 px-3 font-medium",children:A(m.metrics.peakCapital)},m.scenario.id))]})]})]})})]})]})}const Ke=[30,58,95],os=[201,162,39],At=[120,120,120],Et=[40,40,40],It=[34,139,84],Ft=[192,60,60];function he(t){return A(t)}function ui({results:t,preparedBy:x}){const{assumptions:s,yearlySummaries:i,monthlyProjections:l,peakCapitalDeployment:u,breakEvenMonth:r}=t,d=new ks({unit:"mm",format:"letter"}),M=d.internal.pageSize.getWidth(),b=d.internal.pageSize.getHeight(),c=16,p=(C,K)=>{d.setFillColor(...Ke),d.rect(0,0,M,28,"F"),d.setFillColor(...os),d.rect(0,28,M,1.4,"F"),d.setTextColor(255,255,255),d.setFontSize(11),d.setFont("helvetica","normal"),d.text("FREEDOM HEALTHWORKS · 3-YEAR FINANCIAL PROJECTION",c,11),d.setFontSize(16),d.setFont("helvetica","bold"),d.text(C,c,21),K&&(d.setFont("helvetica","normal"),d.setFontSize(9),d.text(K,M-c,21,{align:"right"}))},E=(C,K)=>{d.setDrawColor(220,220,220),d.line(c,b-14,M-c,b-14),d.setFont("helvetica","normal"),d.setFontSize(8),d.setTextColor(...At);const G=`Generated ${new Date().toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"})}${x?` · Prepared by ${x}`:""}`;d.text(G,c,b-9),d.text(`Page ${C} of ${K}`,M-c,b-9,{align:"right"}),d.text("Confidential â Projection based on stated assumptions; actual results may vary.",M/2,b-5,{align:"center"})};p(s.clientName||"Untitled Practice",`${s.projectionYears}-year projection`);let g=42;d.setTextColor(...Et),d.setFont("helvetica","normal"),d.setFontSize(10);const O=new Date(s.startupDate).toLocaleDateString("en-US",{month:"long",day:"numeric",year:"numeric"});d.text(`Projected opening: ${O}`,c,g),g+=8;const v=i[0],W=i[i.length-1],S=[{label:"Year 1 Revenue",value:he(v.totalRevenue),sub:`${v.endingPatients} patients`},{label:"Year 3 Revenue",value:he(W.totalRevenue),sub:`${W.endingPatients} patients`},{label:"Break-Even",value:r?`Month ${r}
20`:"Not in window",sub:r?`Year ${Math.ceil(r/12)}`:"â",color:r&&r<=18?It:Ft},{label:"Peak Capital Need",value:he(u),sub:"Through breakeven"},{label:"Year 3 Net Income",value:he(W.netIncome),sub:"After all expenses",color:W.netIncome>=0?It:Ft},{label:"Year 3 Physician Comp",value:he(W.physicianTotalComp),sub:"Salary + profit share"}],n=(M-c*2-8)/3,X=24;S.forEach((C,K)=>{const Q=K%3,G=Math.floor(K/3),te=c+Q*(n+4),Z=g+G*(X+4);d.setFillColor(248,250,252),d.setDrawColor(220,224,230),d.roundedRect(te,Z,n,X,2,2,"FD"),d.setFont("helvetica","normal"),d.setFontSize(8),d.setTextColor(...At),d.text(C.label.toUpperCase(),te+4,Z+5),d.setFont("helvetica","bold"),d.setFontSize(13),d.setTextColor(...C.color||Ke),d.text(C.value,te+4,Z+13),C.sub&&(d.setFont("helvetica","normal"),d.setFontSize(8),d.setTextColor(...At),d.text(C.sub,te+4,Z+19))}),g+=X*2+4+8,d.setTextColor(...Ke),d.setFont("helvetica","bold"),d.setFontSize(11),d.text("Assumptions driving these numbers",c,g),g+=5;const y=s.pricingMode||"four_tier",_=mt(s),w=y==="flat"?`Flat ${he(s.flatPricePerMonth||0)}/mo`:y==="two_tier"?(s.customTiers||[]).map(C=>`${C.label}: ${he(C.pricePerMonth)} (${Math.round((C.weighting||0)*100)}%)`).join(" · "):[s.infantWeighting>0&&`Infant ${he(s.infantPricePerMonth)} (${Math.round(s.infantWeighting*100)}%)`,s.childWeighting>0&&`Child ${he(s.childPricePerMonth)} (${Math.round(s.childWeighting*100)}%)`,s.adultWeighting>0&&`Adult ${he(s.adultPricePerMonth)} (${Math.round(s.adultWeighting*100)}%)`,s.seniorWeighting>0&&`Senior ${he(s.seniorPricePerMonth)} (${Math.round(s.seniorWeighting*100)}%)`].filter(Boolean).join(" · "),h=s.softwareRampPrice!==void 0?`${he(s.softwareRampPrice)}/mo ramp -> ${he(s.softwareEmrMonthly)}/mo (after ${s.softwareRampUntilPatients} patients or month ${s.softwareRampMaxMonths})`:`${he(s.softwareEmrMonthly||0)}/mo`,T=s.tbdFields||[],U=C=>T.includes(C),j=[["Pricing",w||"â"],["Blended price",`${he(_)} / month`],["Lease",`${he(s.rent||0)} / month`,U("rent")],["Malpractice",`${he(s.malpracticeInsurance||0)} / year`,U("malpracticeInsurance")],["Software / EMR",h,U("softwareEmrMonthly")],["Staff wages",s.staffWagesMonthly?`${he(s.staffWagesMonthly)}/mo after ${s.staffStartAtPatients} patients`:"â",U("staffWagesMonthly")],["Patient growth",`${s.growthRateMonths1to6}/mo (M1-6) -> ${s.growthRateMonths7to12}/mo (M7-12) -> ${s.growthRateYear2Plus}/mo (Y2+)`],["Max panel",s.enableMaxPanel?`${s.maxPatientPanel} patients`:"Uncapped"]];if(ct(d,{startY:g,head:[],body:j.map(([C,K,Q])=>[C,Q?`${K} [TBD]`:K]),theme:"plain",styles:{fontSize:9,cellPadding:{top:1.6,bottom:1.6,left:0,right:0},textColor:Et},columnStyles:{0:{textColor:At,cellWidth:50},1:{fontStyle:"bold"}},didParseCell:C=>{var Q;((Q=j[C.row.index])==null?void 0:Q[2])&&C.column.index===1&&(C.cell.styles.textColor=[180,120,20])},margin:{left:c,right:c}}),g=d.lastAutoTable.finalY+6,s.scenarioNotes){d.setFillColor(246,244,235),d.setDrawColor(...os),d.roundedRect(c,g,M-c*2,18,2,2,"FD"),d.setTextColor(...Ke),d.setFont("helvetica","bold"),d.setFontSize(9),d.text("Notes",c+3,g+5),d.setFont("helvetica","normal"),d.setTextColor(...Et);const C=d.splitTextToSize(s.scenarioNotes,M-c*2-6);d.text(C,c+3,g+10),g+=22}T.length>0&&(d.setTextColor(180,120,20),d.setFont("helvetica","italic"),d.setFontSize(8),d.text(`${T.length} input(s) flagged TBD â confirm with client before treating as final.`,c,g),g+=5),d.addPage(),p("Annual Profit & Loss",s.clientName),ct(d,{startY:38,head:[["",...i.map(C=>`Year ${C.year}`)]],body:[["Patients (year end)",...i.map(C=>String(C.endingPatients))],["Total Revenue",...i.map(C=>he(C.totalRevenue))],["Cost of Service",...i.map(C=>`(${he(C.totalCOS)})`)],["SG&A",...i.map(C=>`(${he(C.totalSGA)})`)],["Net Operating Income",...i.map(C=>he(C.netIncome))],["Physician Comp",...i.map(C=>he(C.physicianTotalComp))]],theme:"striped",headStyles:{fillColor:Ke,textColor:255,fontStyle:"bold",fontSize:10},styles:{fontSize:9,cellPadding:2.4},columnStyles:{0:{fontStyle:"bold",textColor:Ke,cellWidth:55}},didParseCell:C=>{var K;if(C.column.index>0&&C.section==="body"&&(C.cell.styles.halign="right",C.row.index===4)){const Q=((K=i[C.column.index-1])==null?void 0:K.netIncome)??0;C.cell.styles.textColor=Q>=0?It:Ft,C.cell.styles.fontStyle="bold"}},margin:{left:c,right:c}});let R=d.lastAutoTable.finalY+8;d.setTextColor(...Ke),d.setFont("helvetica","bold"),d.setFontSize(11),d.text("Year-by-year notes",c,R),R+=5,d.setFont("helvetica","normal"),d.setFontSize(9),d.setTextColor(...Et),i.map(C=>{const K=C.totalRevenue>0?C.netIncome/C.totalRevenue*100:0;return`⢠Year ${C.year}: ${C.endingPatients} patients, ${he(C.totalRevenue)} revenue, ${K>=0?"+":""}${K.toFixed(1)}% margin.`}
20).forEach((C,K)=>d.text(C,c,R+K*5)),d.addPage(),p("Monthly Detail",s.clientName),ct(d,{startY:38,head:[["Month","Patients","Revenue","COS","SG&A","Net Income","Cum. Cash"]],body:l.map(C=>[C.date,String(C.endingPatients),he(C.totalRevenue),`(${he(C.totalCOS)})`,`(${he(C.totalSGA)})`,he(C.netOperatingIncome),he(C.cumulativeCash)]),theme:"striped",headStyles:{fillColor:Ke,textColor:255,fontStyle:"bold",fontSize:9},styles:{fontSize:8,cellPadding:1.6},columnStyles:{0:{fontStyle:"bold"},1:{halign:"right"},2:{halign:"right"},3:{halign:"right"},4:{halign:"right"},5:{halign:"right"},6:{halign:"right"}},didParseCell:C=>{var K;if(C.section==="body"&&C.column.index===5){const Q=((K=l[C.row.index])==null?void 0:K.netOperatingIncome)??0;Q<0?C.cell.styles.textColor=Ft:Q>0&&(C.cell.styles.textColor=It)}},margin:{left:c,right:c,bottom:18}});const ee=d.internal.getNumberOfPages();for(let C=1;C<=ee;C++)d.setPage(C),E(C,ee);const z=(s.clientName||"Practice").replace(/[^a-z0-9]+/gi,"_");d.save(`${z}_3yr_Projection.pdf`)}function xi({results:t,explanations:x,onBack:s}){const{assumptions:i,yearlySummaries:l,monthlyProjections:u,peakCapitalDeployment:r,breakEvenMonth:d}=t,[M,b]=F.useState([]),{user:c}=ga(),p=l[0],E=l[l.length-1];F.useEffect(()=>{(async()=>{try{const{data:W,error:S}=await at.from("practice_benchmarks").select("*");if(S){console.error("Error fetching benchmarks:",S);return}b(W||[])}catch(W){console.error("Error fetching benchmarks:",W)}})()},[]);const g=()=>{Is({results:t,benchmarks:M})},O=()=>{var W;const v=((W=c==null?void 0:c.user_metadata)==null?void 0:W.full_name)||(c==null?void 0:c.email)||void 0;ui({results:t,preparedBy:v})};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(V,{variant:"ghost",size:"icon",onClick:s,children:e.jsx(pt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:i.clientName})]}),e.jsxs("p",{className:"text-muted-foreground",children:[i.projectionYears,"-year financial projection"]})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(V,{className:"gap-2",onClick:O,children:[e.jsx(xa,{className:"h-4 w-4"}),"Client-Ready PDF"]}),e.jsxs(V,{variant:"outline",className:"gap-2",onClick:g,children:[e.jsx(Sa,{className:"h-4 w-4"}),"Excel"]})]})]}),e.jsxs(me,{className:"animate-slide-up overflow-hidden border-primary/20",children:[e.jsx("div",{className:"bg-gradient-to-br from-primary via-primary to-primary/80 text-primary-foreground px-6 py-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"text-xs uppercase tracking-[0.18em] opacity-75",children:[i.projectionYears,"-Year Outlook"]}),e.jsx("h2",{className:"text-2xl font-bold mt-1",children:i.clientName||"Untitled Practice"}),e.jsxs("p",{className:"text-sm opacity-90 mt-1",children:["Opening ",new Date(i.startupDate).toLocaleDateString("en-US",{month:"long",year:"numeric"})," · ","Break-even ",d?`month ${d}`:"beyond projection window"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.18em] opacity-75",children:"Peak Capital"}),e.jsx("p",{className:"text-2xl font-bold",children:A(r)})]})]})}),e.jsx(le,{className:"pt-5 pb-5",children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-1",children:"Year 1 Patients"}),e.jsx("p",{className:"text-2xl font-bold",children:p.endingPatients})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-1",children:"Year 1 Revenue"}),e.jsx("p",{className:"text-2xl font-bold",children:A(p.totalRevenue)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-1",children:"Year 1 Net Income"}),e.jsx("p",{className:de("text-2xl font-bold",p.netIncome>=0?"text-success":"text-destructive"),children:A(p.netIncome)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-muted-foreground mb-1",children:"Year 1 Physician Comp"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:A(p.physicianTotalComp)})]})]})})]}),e.jsx(di,{assumptions:i,results:t}),e.jsx(oi,{assumptions:i}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(kt,{title:"Year 3 Revenue",value:A(E.totalRevenue),trend:"up",trendValue:`+${((E.totalRevenue/p.totalRevenue-1)*100).toFixed(0)}%`,tooltip:"Total revenue in final projection year",icon:e.jsx(_t,{className:"h-5 w-5"}),delay:0}),e.jsx(kt,{title:"Year 3 Physician Comp",value:A(E.physicianTotalComp),subtitle:`Salary + ${A(E.physicianBonus)} bonus`,trend:"up",tooltip:"Total physician compensation including profit bonus",
20icon:e.jsx(Fn,{className:"h-5 w-5"}),delay:50}),e.jsx(kt,{title:"Peak Capital Needed",value:A(r),tooltip:"Maximum working capital required before break-even",icon:e.jsx(Rs,{className:"h-5 w-5"}),delay:100}),e.jsx(kt,{title:"Break-Even",value:d?`Month ${d}`:"N/A",subtitle:d?`Year ${Math.ceil(d/12)}`:void 0,trend:d&&d<=12?"up":"neutral",tooltip:"Month when cumulative profit turns positive",icon:e.jsx(fs,{className:"h-5 w-5"}),delay:150})]}),e.jsxs(me,{className:"animate-slide-up",style:{animationDelay:"100ms"},children:[e.jsxs(Ce,{children:[e.jsx(Ae,{children:"Annual Summary"}),e.jsx(ke,{children:"Key metrics by year"})]}),e.jsx(le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(gt,{children:[e.jsx(ft,{children:e.jsxs(ae,{children:[e.jsx(Ne,{}),l.map(v=>e.jsxs(Ne,{className:"text-right",children:["Year ",v.year]},v.year))]})}),e.jsxs(jt,{children:[e.jsxs(ae,{children:[e.jsx(I,{className:"font-medium",children:"Patients (yr. end)"}),l.map(v=>e.jsx(I,{className:"text-right",children:v.endingPatients},v.year))]}),e.jsxs(ae,{children:[e.jsx(I,{className:"font-medium",children:"Revenue"}),l.map(v=>e.jsx(I,{className:"text-right",children:A(v.totalRevenue)},v.year))]}),e.jsxs(ae,{children:[e.jsx(I,{className:"font-medium",children:"Less Direct Costs"}),l.map(v=>e.jsxs(I,{className:"text-right text-muted-foreground",children:["(",A(v.totalCOS),")"]},v.year))]}),e.jsxs(ae,{children:[e.jsx(I,{className:"font-medium",children:"Less SG&A Costs"}),l.map(v=>e.jsxs(I,{className:"text-right text-muted-foreground",children:["(",A(v.totalSGA),")"]},v.year))]}),e.jsxs(ae,{className:"bg-muted/30",children:[e.jsx(I,{className:"font-semibold",children:"Net Ordinary Income"}),l.map(v=>e.jsx(I,{className:de("text-right font-semibold",v.netIncome>=0?"text-success":"text-destructive"),children:A(v.netIncome)},v.year))]}),e.jsxs(ae,{children:[e.jsx(I,{className:"font-medium",children:"Physician Salary"}),l.map(v=>e.jsx(I,{className:"text-right",children:A(v.physicianSalary)},v.year))]}),e.jsxs(ae,{children:[e.jsx(I,{className:"font-medium",children:"Physician Bonus"}),l.map(v=>e.jsx(I,{className:"text-right text-success",children:A(v.physicianBonus)},v.year))]}),e.jsxs(ae,{className:"bg-primary/5",children:[e.jsx(I,{className:"font-semibold",children:"Physician Total Comp"}),l.map(v=>e.jsx(I,{className:"text-right font-bold text-primary",children:A(v.physicianTotalComp)},v.year))]})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(Jn,{projections:u,yearlySummaries:l}),e.jsx(ei,{yearlySummaries:l,selectedYear:1})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsx(rs,{assumptions:i,totalPatients:p.endingPatients,year:1}),e.jsx(rs,{assumptions:i,totalPatients:E.endingPatients,year:i.projectionYears})]}),e.jsx(mi,{monthlyProjections:u,assumptions:i}),e.jsx(hi,{baseAssumptions:i}),e.jsx(si,{results:t}),e.jsx(li,{results:t}),e.jsxs(me,{className:"animate-slide-up",style:{animationDelay:"150ms"},children:[e.jsxs(Ce,{children:[e.jsx(Ae,{children:"Monthly Breakdown"}),e.jsx(ke,{children:"Detailed monthly projections"})]}),e.jsx(le,{children:e.jsxs(Na,{defaultValue:"financials",children:[e.jsxs(ba,{className:"mb-4",children:[e.jsx(Ue,{value:"financials",children:"Financials"}),e.jsx(Ue,{value:"patients",children:"Patients"})]}),e.jsx(He,{value:"financials",children:e.jsx("div",{className:"overflow-x-auto max-h-[400px]",children:e.jsxs(gt,{children:[e.jsx(ft,{className:"sticky top-0 bg-card",children:e.jsxs(ae,{children:[e.jsx(Ne,{className:"sticky left-0 bg-card",children:"Month"}),e.jsx(Ne,{className:"text-right",children:"Revenue"}),e.jsx(Ne,{className:"text-right",children:"COS"}),e.jsx(Ne,{className:"text-right",children:"SG&A"}),e.jsx(Ne,{className:"text-right",children:"Net Income"}),e.jsx(Ne,{className:"text-right",children:"Cumulative"})]})}),e.jsx(jt,{children:u.map(v=>e.jsxs(ae,{children:[e.jsx(I,{className:"sticky left-0 bg-card font-medium",children:v.date}),e.jsx(I,{className:"text-right",children:A(v.totalRevenue)}),e.jsxs(I,{className:"text-right text-muted-foreground",children:["(",A(v.totalCOS),")"]}),e.jsxs(I,{className:"text-right text-muted-foreground",children:["(",A(v.totalSGA),")"]}),e.jsx(I,{className:de("text-right font-medium",v.netOperatingIncome>=0?"text-success":"text-destructive"),children:A(v.netOperatingIncome)}),e.jsx(I,{className:de("text-right",v.cumulativeProfit>=0?"text-success":"text-destructive"),children:A(v.cumulativeProfit)})]},v.month))})]})})}),e.jsx(He,{value:"patients",children:e.jsx("div",{className:"overflow-x-auto max-h-[400px]",children:e.jsxs(gt,{children:[e.jsx(ft,{className:"sticky top-0 bg-card",children:e.jsxs(ae,{children:[e.jsx(Ne,{className:"sticky left-0 bg-card",children:"Month"}),e.jsx(Ne,{className:"text-right",children:"Beginning"}),e.jsx(Ne,{className:"text-right",children:"Growth"}),e.jsx(Ne,{className:"text-right",children:"Attrition"}),e.jsx(Ne,{className:"text-right",children:"Ending"})]})}),e.jsx(jt,{children:u.map(v=>e.jsxs(ae,{children:[e.jsx(I,{className:"sticky left-0 bg-card font-medium",children:v.date}),e.jsx(I,{className:"text-right",children:v.beginningPatients}),e.jsxs(I,{className:"text-right text-success",children:["+",v.patientGrowth]}),e.jsxs(I,{className:"text-right text-destructive",children:["-",v.attrition]}),e.jsx(I,{className:"text-right font-medium",children:v.endingPatients})]},v.month))})]})})})]})})]}),e.jsx(ti,{explanations:x}),e.jsx(me,{className:"bg-muted/30 border-muted",children:e.jsx(le,{className:"pt-6",children:e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:[e.jsx("strong",{children:"Notes:"}
20)," These estimates are based on stated assumptions and are not warranted or guaranteed in any way. Model assumes standard Freedom Healthworks services at time of calculation. Individual physician decisions and services do impact net results. Market conditions can vary and impact practice performance unfavorably or favorably. Estimates are for general informational purposes only. Individuals should build their own pro forma calculations of profit and loss."]})})})]})}const ve={conservative:{type:"conservative",label:"Conservative",description:"Lower growth rates, higher attrition",color:"hsl(38, 92%, 50%)"},moderate:{type:"moderate",label:"Moderate",description:"Baseline assumptions from your model",color:"hsl(221, 83%, 53%)"},aggressive:{type:"aggressive",label:"Aggressive",description:"Higher growth rates, lower attrition",color:"hsl(160, 84%, 39%)"}},pi={conservative:{growthMultiplier:.5,attritionMultiplier:2},aggressive:{growthMultiplier:1.5,attritionMultiplier:.5}};function Fs(t,x){if(x==="moderate")return{...t};const s=pi[x];return{...t,growthRateMonths1to6:Math.round(t.growthRateMonths1to6*s.growthMultiplier),growthRateMonths7to12:Math.round(t.growthRateMonths7to12*s.growthMultiplier),growthRateYear2Plus:Math.round(t.growthRateYear2Plus*s.growthMultiplier),attritionRate:Math.round(t.attritionRate*s.attritionMultiplier*10)/10}}function Xe(t,x){const s=Fs(t,x);return{growthRateMonths1to6:s.growthRateMonths1to6,growthRateMonths7to12:s.growthRateMonths7to12,growthRateYear2Plus:s.growthRateYear2Plus,attritionRate:s.attritionRate,patientsAtInception:s.patientsAtInception}}const Tt=({active:t,payload:x,label:s})=>t&&x&&x.length?e.jsxs("div",{className:"bg-card border border-border rounded-lg shadow-lg p-4",children:[e.jsx("p",{className:"font-medium text-foreground mb-2",children:s}),x.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between gap-4 text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:i.color}}),i.name]}),e.jsx("span",{className:"font-medium",children:typeof i.value=="number"&&i.value>100?A(i.value):i.value})]},l))]}):null;function gi({baseAssumptions:t,onBack:x}){const s=F.useMemo(()=>["conservative","moderate","aggressive"].map(c=>{const p=Fs(t,c);return{type:c,results:yt(p)}}),[t]),i=b=>s.find(c=>c.type===b).results,l=F.useMemo(()=>{const b=t.projectionYears,c=[];for(let p=1;p<=b;p++){const E={year:`Year ${p}`};s.forEach(g=>{const O=g.results.yearlySummaries.find(v=>v.year===p);O&&(E[`${g.type}Revenue`]=O.totalRevenue,E[`${g.type}NetIncome`]=O.netIncome,E[`${g.type}PhysComp`]=O.physicianTotalComp,E[`${g.type}Patients`]=O.endingPatients)}),c.push(E)}return c},[s,t.projectionYears]),u=F.useMemo(()=>{const b=[],c=t.projectionYears*12;for(let p=1;p<=c;p+=3){const E={month:`M${p}`};s.forEach(g=>{const O=g.results.monthlyProjections.find(v=>v.month===p);O&&(E[g.type]=O.endingPatients)}),b.push(E)}return b},[s,t.projectionYears]),r=i("conservative"),d=i("moderate"),M=i("aggressive");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(V,{variant:"ghost",size:"icon",onClick:x,children:e.jsx(pt,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(dt,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.clientName})]}),e.jsx("p",{className:"text-muted-foreground",children:"Scenario Comparison Analysis"})]})]}),e.jsxs(V,{variant:"outline",className:"gap-2",children:[e.jsx(Sa,{className:"h-4 w-4"}),"Export Comparison"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:["conservative","moderate","aggressive"].map((b,c)=>{const p=ve[b],E=i(b),g=E.yearlySummaries[E.yearlySummaries.length-1];return e.jsxs(me,{className:"animate-slide-up border-2",style:{animationDelay:`${c*50}ms`,borderColor:`${p.color}30`},children:[e.jsxs(Ce,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"px-3 py-1 rounded-full text-xs font-semibold",style:{backgroundColor:`${p.color}20`,color:p.color},children:p.label}),b==="moderate"&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Baseline"})]}),e.jsx(ke,{className:"text-xs",children:p.description})]}),e.jsxs(le,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Year 3 Revenue"}),e.jsx("p",{className:"text-lg font-bold",children:A(g.totalRevenue)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Year 3 Net Income"}),e.jsx("p",{className:de("text-lg font-bold",g.netIncome>=0?"text-success":"text-destructive"),children:A(g.netIncome)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Final Patients"}),e.jsx("p",{className:"text-lg font-bold",children:g.endingPatients})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Physician Comp"}),e.jsx("p",{className:"text-lg font-bold",style:{color:p.color},children:A(g.physicianTotalComp)})]})]}),e.jsxs("div",{className:"pt-2 border-t border-border",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Peak Capital"}),e.jsx("span",{className:"font-medium",children:A(E.peakCapitalDeployment)})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Break-Even"}),e.jsx("span",{className:"font-medium",children:E.breakEvenMonth?`Month ${E.breakEvenMonth}`:"N/A"})]})]})]})]},b)})}),e.jsxs(me,{className:"animate-slide-up",style:{animationDelay:"150ms"},children:[e.jsxs(Ce,{children:[e.jsx(Ae,{children:"Detailed Comparison"}),e.jsx(ke,{children:"Side-by-side metrics across all scenarios"})]}),e.jsx(le,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(gt,{children:[e.jsx(ft,{children:e.jsxs(ae,{children:[e.jsx(Ne,{children:"Metric"}),e.jsx(Ne,{className:"text-center",style:{color:ve.conservative.color},children:"Conservative"}),e.jsx(Ne,{className:"text-center",style:{color:ve.moderate.color},children:"Moderate"}),e.jsx(Ne,{className:"text-center",style:{color:ve.aggressive.color},children:"Aggressive"})]})}),e.jsxs(jt,{children:[e.jsx(ae,{className:"bg-muted/30",children:e.jsx(I,{colSpan:4,className:"font-semibold",children:"Growth Assumptions"})}),e.jsxs(ae,{children:[e.jsx(I,{children:"Initial Patients"}),e.jsx(I,{className:"text-center",children:Xe(t,"conservative").patientsAtInception}),e.jsx(I,{className:"text-center",children:t.patientsAtInception}),e.jsx(I,{className:"text-center",children:Xe(t,"aggressive").patientsAtInception})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Growth/Mo (M1-6)"}),e.jsx(I,{className:"text-center",children:Xe(t,"conservative").growthRateMonths1to6}),e.jsx(I,{className:"text-center",children:t.growthRateMonths1to6}),e.jsx(I,{className:"text-center",children:Xe(t,"aggressive").growthRateMonths1to6})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Growth/Mo (M7-12)"}),e.jsx(I,{className:"text-center",children:Xe(t,"conservative").growthRateMonths7to12}),e.jsx(I,{className:"text-center",children:t.growthRateMonths7to12}),e.jsx(I,{className:"text-center",children:Xe(t,"aggressive").growthRateMonths7to12})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Attrition Rate"}),e.jsxs(I,{className:"text-center",children:[Xe(t,"conservative").attritionRate,"%"]}),e.jsxs(I,{className:"text-center",children:[t.attritionRate,"%"]}),e.jsxs(I,{className:"text-center",children:[Xe(t,"aggressive").attritionRate,"%"]})]}),e.jsx(ae,{className:"bg-muted/30",children:e.jsx(I,{colSpan:4,className:"font-semibold",children:"Year 1 Results"})}),e.jsxs(ae,{children:[e.jsx(I,{children:"Ending Patients"}),e.jsx(I,{className:"text-center",children:r.yearlySummaries[0].endingPatients}),e.jsx(I,{className:"text-center",children:d.yearlySummaries[0].endingPatients}),e.jsx(I,{className:"text-center",children:M.yearlySummaries[0].endingPatients})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Revenue"}),e.jsx(I,{className:"text-center",children:A(r.yearlySummaries[0].totalRevenue)}),e.jsx(I,{className:"text-center",children:A(d.yearlySummaries[0].totalRevenue)}),e.jsx(I,{className:"text-center",children:A(M.yearlySummaries[0].totalRevenue)})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Net Income"}),e.jsx(I,{className:de("text-center",r.yearlySummaries[0].netIncome>=0?"text-success":"text-destructive"),children:A(r.yearlySummaries[0].netIncome)}),e.jsx(I,{className:de("text-center",d.yearlySummaries[0].netIncome>=0?"text-success":"text-destructive"),children:A(d.yearlySummaries[0].netIncome)}),e.jsx(I,{className:de("text-center",M.yearlySummaries[0].netIncome>=0?"text-success":"text-destructive"),children:A(M.yearlySummaries[0].netIncome)})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Physician Comp"}),e.jsx(I,{className:"text-center",children:A(r.yearlySummaries[0].physicianTotalComp)}),e.jsx(I,{className:"text-center",children:A(d.yearlySummaries[0].physicianTotalComp)}),e.jsx(I,{className:"text-center",children:A(M.yearlySummaries[0].physicianTotalComp)})]}),e.jsx(ae,{className:"bg-muted/30",children:e.jsxs(I,{colSpan:4,className:"font-semibold",children:["Year ",t.projectionYears," Results"]})}),e.jsxs(ae,{children:[e.jsx(I,{children:"Ending Patients"}),e.jsx(I,{className:"text-center",children:r.yearlySummaries[t.projectionYears-1].endingPatients}),e.jsx(I,{className:"text-center",children:d.yearlySummaries[t.projectionYears-1].endingPatients}),e.jsx(I,{className:"text-center",children:M.yearlySummaries[t.projectionYears-1].endingPatients})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Revenue"}),e.jsx(I,{className:"text-center",children:A(r.yearlySummaries[t.projectionYears-1].totalRevenue)}),e.jsx(I,{className:"text-center",children:A(d.yearlySummaries[t.projectionYears-1].totalRevenue)}),e.jsx(I,{className:"text-center",children:A(M.yearlySummaries[t.projectionYears-1].totalRevenue)})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Net Income"}),e.jsx(I,{className:de("text-center font-semibold",r.yearlySummaries[t.projectionYears-1].netIncome>=0?"text-success":"text-destructive"),children:A(r.yearlySummaries[t.projectionYears-1].netIncome)}),e.jsx(I,{className:de("text-center font-semibold",d.yearlySummaries[t.projectionYears-1].netIncome>=0?"text-success":"text-destructive"),children:A(d.yearlySummaries[t.projectionYears-1].netIncome)}),e.jsx(I,{className:de("text-center font-semibold",M.yearlySummaries[t.projectionYears-1].netIncome>=0?"text-success":"text-destructive"),children:A(M.yearlySummaries[t.projectionYears-1].netIncome)})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Physician Comp"}),e.jsx(I,{className:"text-center font-semibold",style:{color:ve.conservative.color},children:A(r.yearlySummaries[t.projectionYears-1].physicianTotalComp)}),e.jsx(I,{className:"text-center font-semibold",style:{color:ve.moderate.color},children:A(d.yearlySummaries[t.projectionYears-1].physicianTotalComp)}),e.jsx(I,{className:"text-center font-semibold",style:{color:ve.aggressive.color},children:A(M.yearlySummaries[t.projectionYears-1].physicianTotalComp)})]}),e.jsx(ae,{className:"bg-muted/30",children:e.jsx(I,{colSpan:4,className:"font-semibold",children:"Key Milestones"})}),e.jsxs(ae,{children:[e.jsx(I,{children:"Peak Capital Required"}),e.jsx(I,{className:"text-center",children:A(r.peakCapitalDeployment)}),e.jsx(I,{className:"text-center",children:A(d.peakCapitalDeployment)}),e.jsx(I,{className:"text-center",children:A(M.peakCapitalDeployment)})]}),e.jsxs(ae,{children:[e.jsx(I,{children:"Break-Even Month"}),e.jsx(I,{className:"text-center",children:r.breakEvenMonth?`Month ${r.breakEvenMonth}`:"N/A"}),e.jsx(I,{className:"text-center",children:d.breakEvenMonth?`Month ${d.breakEvenMonth}`:"N/A"}),e.jsx(I,{className:"text-center",children:M.breakEvenMonth?`Month ${M.breakEvenMonth}`:"N/A"})]})]})]})})})]}),e.jsxs(me,{className:"animate-slide-up",style:{animationDelay:"200ms"},children:[e.jsxs(Ce,{children:[e.jsx(Ae,{children:"Visual Comparison"}),e.jsx(ke,{children:"Charts comparing scenarios across key metrics"})]}),e.jsx(le,{children:e.jsxs(Na,{defaultValue:"revenue",children:[e.jsxs(ba,{className:"mb-4",children:[e.jsx(Ue,{value:"revenue",children:"Revenue"}),e.jsx(Ue,{value:"income",children:"Net Income"}),e.jsx(Ue,{value:"compensation",children:"Physician Comp"}),e.jsx(Ue,{value:"patients",children:"Patient Growth"})]}),e.jsx(He,{value:"revenue",children:e.jsx("div",{className:"h-[400px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(ot,{data:l,margin:{top:20,right:30,left:2
200,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"year",tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:b=>`$${(b/1e3).toFixed(0)}k`}),e.jsx(De,{content:e.jsx(Tt,{})}),e.jsx(Ge,{}),e.jsx(be,{dataKey:"conservativeRevenue",name:"Conservative",fill:ve.conservative.color,radius:[4,4,0,0]}),e.jsx(be,{dataKey:"moderateRevenue",name:"Moderate",fill:ve.moderate.color,radius:[4,4,0,0]}),e.jsx(be,{dataKey:"aggressiveRevenue",name:"Aggressive",fill:ve.aggressive.color,radius:[4,4,0,0]})]})})})}),e.jsx(He,{value:"income",children:e.jsx("div",{className:"h-[400px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(ot,{data:l,margin:{top:20,right:30,left:20,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"year",tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:b=>`$${(b/1e3).toFixed(0)}k`}),e.jsx(De,{content:e.jsx(Tt,{})}),e.jsx(Ge,{}),e.jsx(be,{dataKey:"conservativeNetIncome",name:"Conservative",fill:ve.conservative.color,radius:[4,4,0,0]}),e.jsx(be,{dataKey:"moderateNetIncome",name:"Moderate",fill:ve.moderate.color,radius:[4,4,0,0]}),e.jsx(be,{dataKey:"aggressiveNetIncome",name:"Aggressive",fill:ve.aggressive.color,radius:[4,4,0,0]})]})})})}),e.jsx(He,{value:"compensation",children:e.jsx("div",{className:"h-[400px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(ot,{data:l,margin:{top:20,right:30,left:20,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"year",tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12},tickFormatter:b=>`$${(b/1e3).toFixed(0)}k`}),e.jsx(De,{content:e.jsx(Tt,{})}),e.jsx(Ge,{}),e.jsx(be,{dataKey:"conservativePhysComp",name:"Conservative",fill:ve.conservative.color,radius:[4,4,0,0]}),e.jsx(be,{dataKey:"moderatePhysComp",name:"Moderate",fill:ve.moderate.color,radius:[4,4,0,0]}),e.jsx(be,{dataKey:"aggressivePhysComp",name:"Aggressive",fill:ve.aggressive.color,radius:[4,4,0,0]})]})})})}),e.jsx(He,{value:"patients",children:e.jsx("div",{className:"h-[400px]",children:e.jsx(Te,{width:"100%",height:"100%",children:e.jsxs(Ms,{data:u,margin:{top:20,right:30,left:20,bottom:5},children:[e.jsx(Le,{strokeDasharray:"3 3",stroke:"hsl(var(--border))"}),e.jsx(Ye,{dataKey:"month",tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),e.jsx(Oe,{tick:{fill:"hsl(var(--muted-foreground))",fontSize:12}}),e.jsx(De,{content:e.jsx(Tt,{})}),e.jsx(Ge,{}),e.jsx(Ze,{type:"monotone",dataKey:"conservative",name:"Conservative",stroke:ve.conservative.color,strokeWidth:2,dot:!1}),e.jsx(Ze,{type:"monotone",dataKey:"moderate",name:"Moderate",stroke:ve.moderate.color,strokeWidth:2,dot:!1}),e.jsx(Ze,{type:"monotone",dataKey:"aggressive",name:"Aggressive",stroke:ve.aggressive.color,strokeWidth:2,dot:!1})]})})})})]})})]}),e.jsx(me,{className:"bg-muted/30 border-muted",children:e.jsx(le,{className:"pt-6",children:e.jsxs("p",{className:"text-xs text-muted-foreground leading-relaxed",children:[e.jsx("strong",{children:"Scenario Comparison Notes:"})," Conservative assumes lower initial patients (80), slower growth rates, and higher attrition (2.5%). Aggressive assumes higher initial patients (120), faster growth, and lower attrition (1.0%). These scenarios help illustrate the range of potential outcomes based on different market conditions and execution."]})})})]})}const cs={clientName:"Practice Name",zipCode:"ZIP Code",startupDate:"Startup Date",projectionYears:"Projection Years",practiceModel:"Practice Model",practiceSpecialty:"Practice Specialty",infantPricePerMonth:"Infant Price/Month (0-2)",childPricePerMonth:"Child Price/Month (3-17)",adultPricePerMonth:"Adult Price/Month (18-64)",seniorPricePerMonth:"Senior Price/Month (65+)",infantWeighting:"Infant Mix %",childWeighting:"Child Mix %",adultWeighting:"Adult Mix %",seniorWeighting:"Senior Mix %",enrollmentFee:"Enrollment Fee",patientsAtInception:"Pre-Enrolled Patients",growthRateMonths1to6:"Growth (Months 1-6)",growthRateMonths7to12:"Growth (Months 7-12)",growthRateYear2Plus:"Growth (Year 2+)",attritionRate:"Attrition Rate",attritionStartMonth:"Attrition Start Month",enableAttrition:"Enable Attrition",enableMaxPanel:"Enable Max Panel",enableProfitSplit:"Enable Profit Split",maxPatientPanel:"Max Patient Panel",stipendPerMonth:"Monthly Stipend",fdNetworkFee:"FD Network Fee",msoSplit:"MSO Split %",rent:"Rent/Facility",fhManagementPackage:"FH Management Package",physicianSalary:"Physician Salary",revenueSharePercent:"Revenue Share
20%",malpracticeInsurance:"Malpractice Insurance",commercialInsurance:"Commercial Insurance",marketing:"Marketing",internetUtilities:"Internet/Utilities",duesBoardsSubscriptions:"Dues/Subscriptions",officeSupplies:"Office Supplies",printingSupplies:"Printing Supplies",postage:"Postage",travelMeals:"Travel/Meals",otherOperating:"Other Operating",paymentProcessingPercent:"Payment Processing %",softwarePerPatient:"Software/Patient",cogsPerPatient:"COGS/Patient",medicalSuppliesPerPatient:"Med Supplies/Patient",vaccinesMedicationsMargin:"Vaccines Margin %",expenseGrowthRate:"Expense Growth %",marketingDeclineYear4:"Marketing Decline Y4 %",fhLaunchFee:"FH Launch Fee",facilityBuildout:"Facility Buildout",furnitureFixtures:"Furniture & Fixtures",officeEquipment:"Office Equipment",securityDeposit:"Security Deposit",medicalEquipment:"Medical Equipment",initialInventory:"Initial Inventory",medicalSuppliesStartup:"Medical Supplies (Startup)",signageBranding:"Signage & Branding",legalAccounting:"Legal & Accounting",startupMarketing:"Startup Marketing",initialStaffTraining:"Staff Training",enableAncillaryRevenue:"Enable Ancillary Revenue",ancillaryServices:"Ancillary Services",staffWagesMonthly:"Staff Wages (Monthly)",staffStartAtPatients:"Staff Start at Patients",accountingMonthly:"Accounting (Monthly)",softwareEmrMonthly:"Software/EMR (Monthly)"};function fi({onImport:t,onCancel:x}){const[s,i]=F.useState(!1),[l,u]=F.useState([]),[r,d]=F.useState(""),[M,b]=F.useState(""),[c,p]=F.useState(!1),[E,g]=F.useState(0),O=async _=>{var w,h;p(!0),g(30);try{const T=await Tn("analyze-spreadsheet",{body:{spreadsheetData:_}});if(g(80),!T.success||!T.mappings)throw new Error(T.error||"No data extracted");const U=[];for(const[j,R]of Object.entries(T.mappings))R!=null&&j in cs&&U.push({key:j,label:cs[j],value:R,source:((w=T.sources)==null?void 0:w[j])||"AI detected",confidence:((h=T.confidence)==null?void 0:h[j])||.8});return g(100),U}catch(T){throw console.error("AI analysis error:",T),T}finally{p(!1)}},v=F.useCallback(async _=>{b(""),d(_.name),g(10);const w=new FileReader;w.onload=async h=>{var T;try{const U=(T=h.target)==null?void 0:T.result,j=Cs(U,{type:"binary"}),R=[];if(j.SheetNames.forEach(ee=>{const z=j.Sheets[ee],C=We.sheet_to_json(z,{header:1});R.push([`=== Sheet: ${ee} ===`]),R.push(...C.filter(K=>Array.isArray(K)&&K.some(Q=>Q!=null&&Q!=="")))}),R.length===0){b("The spreadsheet appears to be empty.");return}const H=await O(R);H.length===0?b("AI could not identify any financial data. Try a different spreadsheet format."):u(H)}catch(U){console.error("Parse error:",U),b("Failed to analyze spreadsheet. Please try again."),p(!1)}},w.onerror=()=>{b("Failed to read the file. Please try again."),p(!1)},w.readAsBinaryString(_)},[]),W=F.useCallback(_=>{_.preventDefault(),i(!1);const w=_.dataTransfer.files[0];w&&(w.name.endsWith(".xlsx")||w.name.endsWith(".xls")||w.name.endsWith(".csv"))?v(w):b("Please upload an Excel (.xlsx, .xls) or CSV file.")},[v]),S=F.useCallback(_=>{var h;const w=(h=_.target.files)==null?void 0:h[0];w&&v(w)},[v]),n=()=>{const _={};l.forEach(({key:w,value:h})=>{_[w]=h}),t(_)},X=_=>{u(w=>w.filter(h=>h.key!==_))},y=_=>_?_>=.9?"text-success":_>=.7?"text-warning":"text-destructive":"text-muted-foreground";return e.jsxs(me,{className:"animate-slide-up",children:[e.jsx(Ce,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-success/10",children:e.jsx(Ve,{className:"h-5 w-5 text-success"})}),e.jsxs("div",{children:[e.jsx(Ae,{children:"AI-Powered Import"}),e.jsx(ke,{children:"Upload your spreadsheet and AI will extract the values"})]})]})}),e.jsx(le,{className:"space-y-6",children:c?e.jsxs("div",{className:"py-8 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsx(nt,{className:"h-6 w-6 animate-spin text-primary"}),e.jsx("span",{className:"text-lg font-medium",children:"AI is analyzing your spreadsheet..."})]}),e.jsx(Xs,{value:E,className:"w-full max-w-md mx-auto"}),e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"Reading cells, identifying patterns, mapping values"})]}):l.length===0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:` 21 border-2 border-dashed rounded-xl p-8 text-center transition-colors cursor-pointer 22 ${s?"border-primary bg-primary/5":"border-border hover:border-primary/50"} 23 `,onDragOver:_=>{_.preventDefault(),i(!0)},onDragLeave:()=>i(!1),onDrop:W,onClick:()=>{var _;return(_=document.getElementById("file-input"))==null?void 0:_.click()},children:[e.jsx("input",{id:"file-input",type:"file",accept:".xlsx,.xls,.csv",onChange:S,className:"hidden"}),e.jsx(Zs,{className:`h-12 w-12 mx-auto mb-4 ${s?"text-primary":"text-muted-foreground"}`}),e.jsx("p",{className:"text-lg font-medium mb-2",children:s?"Drop your file here":"Drag & drop your spreadsheet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Or click to browse ⢠Supports .xlsx, .xls, .csv"}),e.jsxs(pe,{variant:"secondary",className:"gap-1",children:[e.jsx(Ve,{className:"h-3 w-3"}),"AI will automatically detect and map your data"]})]}),M&&e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-lg bg-destructive/10 border border-destructive/20",children:[e.jsx(Js,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-destructive",children:"Import Error"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:M})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(V,{variant:"ghost",onClick:x,children:"Cancel"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsxs(pe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gt,{className:"h-3 w-3"}),r]}),e.jsxs(pe,{variant:"outline",className:"gap-1",children:[e.jsx(Ve,{className:"h-3 w-3"}),l.length," values detected by AI"]})]}),e.jsx(fa,{className:"h-[300px] rounded-lg border",children:e.jsx("div",{className:"p-4 space-y-2",children:l.map(({key:_,label:w,value:h,source:T,confidence:U})=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm",children:w}),U&&e.jsxs("span",{className:`text-xs ${y(U)}`,children:[Math.round(U*100),"% confident"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:T})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"font-mono text-sm font-semibold text-primary",children:typeof h=="number"&&(w.toLowerCase().includes("price")||w.toLowerCase().includes("salary")||w.toLowerCase().includes("fee")||w.toLowerCase().includes("rent")||w.toLowerCase().includes("insurance")||w.toLowerCase().includes("marketing"))?A(h):typeof h=="number"?h.toLocaleStr
23ing():h}),e.jsx(V,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>X(_),children:e.jsx(ya,{className:"h-4 w-4"})})]})]},_))})}),e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx(V,{variant:"ghost",onClick:()=>{u([]),d(""),b(""),g(0)},children:"Upload Different File"}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx(V,{variant:"outline",onClick:x,children:"Cancel"}),e.jsxs(V,{variant:"gradient",onClick:n,className:"gap-2",children:[e.jsx(va,{className:"h-4 w-4"}),"Import ",l.length," Values"]})]})]})]})})]})}function ji({projections:t,loading:x,onLoad:s,onDelete:i}){const[l,u]=F.useState(""),[r,d]=F.useState(null),M=t.filter(p=>p.name.toLowerCase().includes(l.toLowerCase())),b=async()=>{r&&(await i(r),d(null))},c=p=>new Date(p).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return x?e.jsx(me,{children:e.jsx(le,{className:"py-8",children:e.jsx("div",{className:"flex items-center justify-center text-muted-foreground",children:e.jsx("div",{className:"animate-pulse",children:"Loading saved projections..."})})})}):e.jsxs(e.Fragment,{children:[e.jsxs(me,{className:"animate-slide-up",children:[e.jsx(Ce,{children:e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(zt,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Ae,{children:"Saved Projections"}),e.jsxs(ke,{children:[t.length," projection",t.length!==1?"s":""," saved"]})]})]})})}),e.jsxs(le,{className:"space-y-4",children:[t.length>3&&e.jsxs("div",{className:"relative",children:[e.jsx(Qs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Me,{placeholder:"Search projections...",value:l,onChange:p=>u(p.target.value),className:"pl-10"})]}),M.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:l?"No projections match your search":"No saved projections yet"}):e.jsx("div",{className:"space-y-2",children:M.map(p=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border bg-card hover:bg-muted/50 transition-colors",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("h4",{className:"font-medium truncate",children:p.name}),e.jsxs(pe,{variant:"outline",className:"shrink-0",children:[e.jsx(Qe,{className:"h-3 w-3 mr-1"}),p.assumptions.patientsAtInception," pts"]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(en,{className:"h-3 w-3"}),c(p.updated_at)]}),e.jsxs("span",{children:[A(p.assumptions.adultPricePerMonth),"/mo"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[e.jsx(V,{variant:"outline",size:"sm",onClick:()=>s(p),children:"Load"}),e.jsxs(tn,{children:[e.jsx(an,{asChild:!0,children:e.jsx(V,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Gn,{className:"h-4 w-4"})})}),e.jsx(sn,{align:"end",children:e.jsxs(nn,{className:"text-destructive",onClick:()=>d(p.id),children:[e.jsx(ja,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})]},p.id))})]})]}),e.jsx(Dn,{open:!!r,onOpenChange:()=>d(null),children:e.jsxs(On,{children:[e.jsxs(Bn,{children:[e.jsx(Wn,{children:"Delete Projection?"}),e.jsx(Ln,{children:"This action cannot be undone. This will permanently delete the saved projection."})]}),e.jsxs(Yn,{children:[e.jsx(_n,{children:"Cancel"}),e.jsx(zn,{onClick:b,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}const yi=[{value:"draft",label:"Draft",icon:e.jsx(es,{className:"h-4 w-4"}),description:"Work in progress"},{value:"finalized",label:"Finalized",icon:e.jsx(es,{className:"h-4 w-4"}),description:"Ready for review"},{value:"launched",label:"Launched",icon:e.jsx(on,{className:"h-4 w-4"}),description:"Practice is live"},{value:"archived",label:"Archived",icon:e.jsx(Hn,{className:"h-4 w-4"}),description:"No longer active"}];function ds({open:t,onOpenChange:x,assumptions:s,initialClientId:i,onSave:l}){const[u,r]=F.useState(s.clientName||""),[d,M]=F.useState(""),[b,c]=F.useState("draft"),[p,E]=F.useState(""),[g,O]=F.useState(!1),W=rn().data||[];F.useEffect(()=>{if(t)if(r(s.clientName||""),M(""),c("draft"),i)E(i);else if(s.clientName){const n=W.find(X=>{var y;return X.name.toLowerCase()===((y=s.clientName)==null?void 0:y.toLowerCase())});E((n==null?void 0:n.id)||"")}else E("")},[t,s.clientName,W,i]);const S=async()=>{u.trim()&&(O(!0),await l(u,s,d||void 0,b,p||void 0),O(!1),x(!1))};return e.jsx(ra,{open:t,onOpenChange:x,children:e.jsxs(la,{className:"sm:max-w-md",children:[e.jsxs(oa,{
23children:[e.jsx(ca,{children:"Save Projection"}),e.jsx(da,{children:"Save this projection and optionally link it to a client for tracking."})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"projection-name",children:"Projection Name"}),e.jsx(Me,{id:"projection-name",placeholder:"e.g., Dr. Smith - Conservative Scenario",value:u,onChange:n=>r(n.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"projection-status",children:"Status"}),e.jsxs(Xa,{value:b,onValueChange:n=>c(n),children:[e.jsx(Za,{id:"projection-status",children:e.jsx(Ja,{placeholder:"Select status"})}),e.jsx(Qa,{children:yi.map(n=>e.jsx(Qt,{value:n.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[n.icon,e.jsx("span",{children:n.label}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["â ",n.description]})]})},n.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(Se,{htmlFor:"linked-client",className:"flex items-center gap-2",children:[e.jsx(ln,{className:"h-4 w-4"}),"Link to Client (Optional)"]}),e.jsxs(Xa,{value:p||"none",onValueChange:n=>E(n==="none"?"":n),children:[e.jsx(Za,{id:"linked-client",children:e.jsx(Ja,{placeholder:"Select a client to link..."})}),e.jsxs(Qa,{children:[e.jsx(Qt,{value:"none",children:"No client linked"}),W.map(n=>e.jsxs(Qt,{value:n.id,children:[n.name,n.location_city&&` â ${n.location_city}, ${n.location_state}`]},n.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Linking enables actual vs. projected tracking when the practice launches."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"projection-notes",children:"Notes (optional)"}),e.jsx(Un,{id:"projection-notes",placeholder:"Add any notes about this projection...",value:d,onChange:n=>M(n.target.value),rows:3})]})]}),e.jsxs(ps,{children:[e.jsx(V,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx(V,{variant:"gradient",onClick:S,disabled:!u.trim()||g,children:g?"Saving...":"Save Projection"})]})]})})}const vi=`${pa}/functions/v1/intake-assistant`,ms=[{id:"primary_care",label:"Primary Care",icon:dt,color:"bg-primary/10 text-primary"},{id:"pediatric",label:"Pediatric",icon:Es,color:"bg-success/10 text-success"},{id:"internal_medicine",label:"Internal Medicine",icon:js,color:"bg-warning/10 text-warning"},{id:"specialty",label:"Specialty",icon:cn,color:"bg-destructive/10 text-destructive"},{id:"custom",label:"Custom",icon:ys,color:"bg-muted text-muted-foreground"}];function Ni({onComplete:t,onCancel:x,initialData:s}){const[i,l]=F.useState([]),[u,r]=F.useState(""),[d,M]=F.useState(!1),[b,c]=F.useState(!!(s!=null&&s.clientName)),[p,E]=F.useState(null),[g,O]=F.useState(!1),v=F.useRef(null),W=F.useRef(null),S=F.useRef(null);F.useEffect(()=>{var j;(j=v.current)==null||j.scrollIntoView({behavior:"smooth"})},[i]),F.useEffect(()=>{!d&&W.current&&W.current.focus()},[d]),F.useEffect(()=>{if(s!=null&&s.clientName&&i.length===0&&!d){const j=n(s);X(j)}},[]);const n=j=>{const R=[];if(j.clientName&&R.push(`practice name is "${j.clientName}"`),j.zipCode&&R.push(`located in ZIP ${j.zipCode}`),j.specialty){const H=j.specialty==="pediatric"?"Pediatric":j.specialty==="family"?"Family Medicine":j.specialty==="internal"?"Internal Medicine":"General DPC";R.push(`specialty is ${H}`)}return`I'm setting up projections. The ${R.join(", ")}.`},X=async j=>{var H,ee,z;const R=[...i,{role:"user",content:j}];l(R),M(!0);try{const C=await fetch(vi,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${na}`},body:JSON.stringify({messages:R.map(Z=>({role:Z.role,content:Z.content}))})});if(!C.ok||!C.body){const Z=await C.json().catch(()=>({}));throw new Error(Z.error||"Failed to connect to assistant")}const K=C.body.getReader(),Q=new TextDecoder;let G="",te="";for(l(Z=>[...Z,{role:"assistant",content:""}]);;){const{done:Z,value:m}=await K.read();if(Z)break;te+=Q.decode(m,{stream:!0});let Y;for(;(Y=te.indexOf(` 24`))!==-1;){let L=te.slice(0,Y);if(te=te.slice(Y+1),L.endsWith("\r")&&(L=L.slice(0,-1)),L.startsWith(":")||L.trim()===""||!L.startsWith("data: "))continue;const D=L.slice(6).trim();if(D==="[DONE]")break;try{const fe=(z=(ee=(H=JSON.parse(D).choices)==null?void 0:H[0])==null?void 0:ee.delta)==null?void 0:z.content;
24fe&&(G+=fe,l(P=>{const ue=[...P];return ue[ue.length-1]={role:"assistant",content:G},ue}))}catch{}}}y(G)}catch(C){console.error("Chat error:",C),l(K=>[...K.slice(0,-1),{role:"assistant",content:"I apologize, but I encountered an error. Please try again."}])}finally{M(!1)}},y=j=>{const R=j.match(/```json\s*([\s\S]*?)\s*```/);if(R)try{const H=JSON.parse(R[1]);if(H.complete&&H.assumptions){const ee=_(H.assumptions);setTimeout(()=>t(ee),1500)}}catch(H){console.error("Failed to parse assumptions:",H)}},_=j=>{const R={...Fe};(j.practiceModel==="independent_dpc"||j.practiceModel==="freedomdoc_health")&&(R.practiceModel=j.practiceModel),R.practiceModel==="independent_dpc"&&(R.physicianSalary=0,R.fhManagementPackage=0,R.fdNetworkFee=0,R.revenueSharePercent=0,R.enableProfitSplit=!1,R.msoSplit=0,R.stipendPerMonth=0),j.clientName&&(R.clientName=String(j.clientName)),j.patientsAtInception&&(R.patientsAtInception=Number(j.patientsAtInception)),j.growthRateMonths1to6&&(R.growthRateMonths1to6=Number(j.growthRateMonths1to6)),j.growthRateMonths7to12&&(R.growthRateMonths7to12=Number(j.growthRateMonths7to12)),j.growthRateYear2Plus&&(R.growthRateYear2Plus=Number(j.growthRateYear2Plus)),j.attritionRate&&(R.attritionRate=Number(j.attritionRate)),j.maxPatientPanel&&(R.maxPatientPanel=Number(j.maxPatientPanel)),j.rent&&(R.rent=Number(j.rent)),j.marketing&&(R.marketing=Number(j.marketing)),j.malpracticeInsurance&&(R.malpracticeInsurance=Number(j.malpracticeInsurance)),R.practiceModel==="freedomdoc_health"&&(j.physicianSalary!==void 0&&(R.physicianSalary=Number(j.physicianSalary)),j.msoSplit!==void 0&&(R.msoSplit=Number(j.msoSplit)),j.enableProfitSplit!==void 0&&(R.enableProfitSplit=!!j.enableProfitSplit),j.fdNetworkFee!==void 0&&(R.fdNetworkFee=Number(j.fdNetworkFee)),j.revenueSharePercent!==void 0&&(R.revenueSharePercent=Number(j.revenueSharePercent)),j.fhManagementPackage!==void 0&&(R.fhManagementPackage=Number(j.fhManagementPackage)));const H=j.memberships;H&&H.length>0&&(H[0]&&(R.adultPricePerMonth=H[0].pricePerMonth,R.adultWeighting=H[0].weighting),H[1]&&(R.seniorPricePerMonth=H[1].pricePerMonth,R.seniorWeighting=H[1].weighting),H[2]&&(R.childPricePerMonth=H[2].pricePerMonth,R.childWeighting=H[2].weighting));const ee=j.ancillaryServices;ee&&ee.length>0&&(R.enableAncillaryRevenue=!0,R.ancillaryServices=ee.map(C=>({name:C.name,pricePerService:C.pricePerService,estimatedMonthlyVolume:C.estimatedMonthlyVolume||0,costPerService:C.costPerService||0,enabled:!0})));const z=j.startupCosts;return z&&(z.fhLaunchFee!==void 0&&(R.fhLaunchFee=Number(z.fhLaunchFee)),z.facilityBuildout!==void 0&&(R.facilityBuildout=Number(z.facilityBuildout)),z.securityDeposit!==void 0&&(R.securityDeposit=Number(z.securityDeposit)),z.officeEquipment!==void 0&&(R.officeEquipment=Number(z.officeEquipment)),z.medicalEquipment!==void 0&&(R.medicalEquipment=Number(z.medicalEquipment)),z.initialInventory!==void 0&&(R.initialInventory=Number(z.initialInventory)),z.signageBranding!==void 0&&(R.signageBranding=Number(z.signageBranding)),z.legalAccounting!==void 0&&(R.legalAccounting=Number(z.legalAccounting))),R},w=async j=>{var H;const R=(H=j.target.files)==null?void 0:H[0];if(R){O(!0);try{const ee=R.name.toLowerCase();let z="";if(ee.endsWith(".xlsx")||ee.endsWith(".xls")||ee.endsWith(".csv")){const C=await R.arrayBuffer(),K=Cs(C,{type:"array"});z=K.SheetNames.map(G=>{const te=K.Sheets[G],Z=We.sheet_to_csv(te);return`=== Sheet: ${G} === 25${Z}`}).join(` 26 27`)}else if(ee.endsWith(".txt")||ee.endsWith(".md"))z=await R.text();else if(ee.endsWith(".pdf")){ge.info("Parsing PDF document...");const C=await R.arrayBuffer(),K=btoa(new Uint8Array(C).reduce((te,Z)=>te+String.fromCharCode(Z),"")),Q=await fetch(`${pa}/functions/v1/parse-document`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${na}`},body:JSON.stringify({fileBase64:K,fileName:R.name})});if(!Q.ok){const te=await Q.json().catch(()=>({}));throw new Error(te.error||"Failed to parse PDF")}z=(await Q.json()).content}else{ge.error("Unsupported file type. Please upload PDF, Excel, CSV, or text files.");return}z.length>15e3&&(z=z.substring(0,15e3)+` 28... [truncated]`),E({name:R.name,content:z}),ge.success(`Uploaded ${R.name}`)}catch(ee){console.error("File parsing error:",ee),ge.error(ee instanceof Error?ee.message:"Failed to parse file")}finally{O(!1),S.current&&(S.current.value="")}}},h=()=>
28{if(!u.trim()&&!p||d)return;let j=u.trim();p&&(j=j?`${j} 29 30[UPLOADED DOCUMENT: ${p.name}] 31${p.content}`:`I've uploaded a document for reference: ${p.name} 32 33[DOCUMENT CONTENT] 34${p.content}`,E(null)),X(j),r("")},T=j=>{j.key==="Enter"&&!j.shiftKey&&(j.preventDefault(),h())},U=j=>{c(!0);const R=ms.find(ee=>ee.id===j),H=j==="custom"?"I'd like to set up a custom practice type":`I'm setting up a ${R==null?void 0:R.label} practice`;X(H)};return b?e.jsx(me,{className:"max-w-2xl mx-auto animate-slide-up",children:e.jsxs(le,{className:"p-0",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 border-b",children:[e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:e.jsx(Ve,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold",children:"Practice Setup Assistant"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"AI-guided financial intake"})]}),e.jsx(V,{variant:"ghost",size:"sm",onClick:x,children:"Cancel"})]}),e.jsx(fa,{className:"h-[400px] p-4",children:e.jsxs("div",{className:"space-y-4",children:[i.map((j,R)=>e.jsxs("div",{className:`flex gap-3 ${j.role==="user"?"justify-end":"justify-start"}`,children:[j.role==="assistant"&&e.jsx("div",{className:"p-2 rounded-full bg-primary/10 h-8 w-8 flex items-center justify-center shrink-0",children:e.jsx(Vn,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:` 35 max-w-[80%] rounded-2xl px-4 py-2.5 36 ${j.role==="user"?"bg-primary text-primary-foreground rounded-br-md":"bg-muted rounded-bl-md"} 37 `,children:[e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content.replace(/```json[\s\S]*?```/g,"").trim()||(j.role==="assistant"&&d?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(nt,{className:"h-4 w-4 animate-spin"}),"Thinking..."]}):j.content)}),j.content.includes('"complete": true')&&e.jsxs(pe,{variant:"secondary",className:"mt-2 gap-1",children:[e.jsx(lt,{className:"h-3 w-3"}),"Preparing your projections..."]})]}),j.role==="user"&&e.jsx("div",{className:"p-2 rounded-full bg-secondary h-8 w-8 flex items-center justify-center shrink-0",children:e.jsx(dn,{className:"h-4 w-4"})})]},R)),e.jsx("div",{ref:v})]})}),e.jsxs("div",{className:"p-4 border-t",children:[p&&e.jsx("div",{className:"mb-2",children:e.jsxs(pe,{variant:"secondary",className:"gap-1.5 pr-1",children:[e.jsx(Gt,{className:"h-3 w-3"}),p.name,e.jsx("button",{onClick:()=>E(null),className:"ml-1 p-0.5 rounded hover:bg-muted",children:e.jsx(ya,{className:"h-3 w-3"})})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{ref:S,type:"file",accept:".pdf,.xlsx,.xls,.csv,.txt,.md",onChange:w,className:"hidden"}),e.jsx(V,{type:"button",variant:"outline",size:"icon",onClick:()=>{var j;return(j=S.current)==null?void 0:j.click()},disabled:d||g,title:"Upload document",children:g?e.jsx(nt,{className:"h-4 w-4 animate-spin"}):e.jsx(qn,{className:"h-4 w-4"})}),e.jsx(Me,{ref:W,value:u,onChange:j=>r(j.target.value),onKeyDown:T,placeholder:p?"Add a message or just send...":"Type your response...",disabled:d,className:"flex-1"}),e.jsx(V,{onClick:h,disabled:!u.trim()&&!p||d,size:"icon",children:d?e.jsx(nt,{className:"h-4 w-4 animate-spin"}):e.jsx(mn,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Upload PDF, Excel, CSV, or text files with practice data"})]})]})}):e.jsx(me,{className:"max-w-2xl mx-auto animate-slide-up",children:e.jsxs(le,{className:"pt-8 pb-6",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center p-3 rounded-2xl bg-gradient-to-br from-primary to-[hsl(250,84%,54%)] mb-4",children:e.jsx(Ve,{className:"h-8 w-8 text-primary-foreground"})}),e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-2",children:"AI-Guided Practice Setup"}),e.jsxs("p",{className:"text-muted-foreground",children:["I'll help you set up your financial projections with a few quick questions.",e.jsx("br",{}),"Select your practice type to get started:"]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-6",children:ms.map(j=>{const R=j.icon;return e.jsxs("button",{onClick:()=>U(j.id),className:` 38 flex flex-col items-center gap-2 p-4 rounded-xl border-2 border-transparent 39 hover:border-primary/50 transition-all cursor-pointer 40 ${j.color} 41 `,children:[e.jsx(R,{className:"h-8 w-8"}),e.jsx("span",{className:"font-medium text-sm",children:j.label})]},j.id)})}),e.jsx("div",{className:"flex justify-center",children:e.jsx(V,{variant:"ghost",onClick:x,children:"Use Manual Form Instead"})})]})})}const xt={high:{level:"high",multiplier:1.35,label:"High Cost of Living",examples:"NYC, SF, LA, Boston, Seattle, DC"},medium:{level:"medium",multiplier:1,label:"Medium Cost of Living",examples:"Denver, Austin, Nashville, Charlotte, Phoenix"},low:{level:"low",multiplier:.75,label:"Low Cost of Living",examples:"Indianapolis, Oklahoma City, Kansas City, rural areas"}},bi=new Set(["100","101","102","103","104","105","106","107","108","109","110","111","112","113","114","115","116","117","118","119","940","941","942","943","944","945","946","947","948","949","950","951","900","901","902","903","904","905","906","907","908","910","911","912","913","914","915","916","917","918","020","021","022","023","024","025","980","981","982","983","984","200","201","202","203","204","205","206","207","208","209","220","221","222","223","919","920","921","331","332","333","334","339","340","341","342","967","968","950","951","952","953","954","926","927","928","068","069","070","071","072","073","074","076","077","078","079","115","116","117","118","119","105","106","107","108","931","932","933","945","949"]),Si=new Set(["800","801","802","803","804","805","787","786","370","371","372","280","281","282","850","851","852","853","550","551","553","554","555","600","601","602","603","604","605","606","750","751","752","753","754","760","761","762","770","771","772","773","774","775","300","301","302","303","304","305","306","970","971","972","973","780","781","782","335","336","337","338","327","328","329","275","276","277","840","841","842","889","890","891","430","431","432","433","150","151","152","153","154","190","191","192","193","194","956","957","958","530","531","532","320","321","322","230","231","232","210","211","212","480","481","482","483","484","630","631","633","634","640","641","660","661","662","450","451","452","440","441","442","443","444","871","856","857","836","837","294","313","314","700","701","400","401","402","461","462"]);function Lt(t){const x=t.replace(/\D/g,"").slice(0,5);if(x.length<3)return xt.medium;const s=x.slice(0,3);return bi.has(s)?xt.high:Si.has(s)?xt.medium:xt.low}function wi(t){const x=xt[t].multiplier;return{rent:t==="high"?1.6:t==="low"?.6:1,pricing:x,insurance:t==="high"?1.3:t==="low"?.85:1,marketing:t==="high"?1.25:t==="low"?.8:1,utilities:t==="high"?1.2:t==="low"?.85:1,buildout:t==="high"?1.5:t==="low"?.7:1,professional:t==="high"?1.3:t==="low"?.85:1}}function Yt(t){const x=t.replace(/\D/g,"").slice(0,5);if(x.length<3)return"";const s=x.slice(0,3);return{100:"New York, NY",101:"New York, NY",102:"New York, NY",103:"Staten Island, NY",104:"Bronx, NY",105:"Westchester, NY",110:"Queens, NY",111:"Long Island, NY",112:"Brooklyn, NY",940:"San Francisco, CA",941:"San Francisco, CA",900:"Los Angeles, CA",901:"Los Angeles, CA",902:"Inglewood, CA","020":"Boston, MA","021":"Boston, MA","022":"Boston, MA",980:"Seattle, WA",981:"Seattle, WA",200:"Washington, DC",201:"Washington, DC",202:"Washington, DC",800:"Denver, CO",801:"Denver, CO",802:"Denver, CO",787:"Austin, TX",786:"Austin, TX",370:"Nashville, TN",371:"Nashville, TN",280:"Charlotte, NC",281:"Charlotte, NC",850:"Phoenix, AZ",851:"Phoenix, AZ",852:"Phoenix, AZ",460:"Indianapolis, IN",461:"Indianapolis, IN",462:"Indianapolis, IN",731:"Oklahoma City, OK",730:"Oklahoma City, OK",640:"Kansas City, MO",641:"Kansas City, MO",750:"Dallas, TX",751:"Dallas, TX",752:"Fort Worth, TX",770:"Houston, TX",771:"Houston, TX",772:"Houston, TX",300:"Atlanta, GA",301:"Atlanta, GA",302:"Atlanta, GA",331:"Miami, FL",332:"Miami, FL",333:"Fort Lauderdale, FL",339:"Fort Myers, FL",340:"Naples, FL",341:"Naples, FL",342:"Naples, FL",919:"San Diego, CA",920:"San Diego, CA",921:"San Diego, CA",950:"San Jose, CA",951:"San Jose, CA"}[s]||""}const Pi={...Fe,clientName:"SAGE Direct Primary Care",zipCode:"",startupDate:"2026-12-01",projectionYears:3,practiceModel:"independent_dpc",practiceSpecialty:"family_medicine",pricingMode:"two_tier",customTiers:[{id:"adult",label:"Ages 19-44",pricePerMonth:175,weighting:.6},{id:"senior",label:"Ages 45+",pricePerMonth:225,weighting:.4}],infantPricePerMonth:0,childPricePerMonth:0,adultPricePerMonth:175,seniorPricePerMonth:225,infantWeighting:0,childWeighting:0,adultWeighting:.6,seniorWeighting:.4,enrollmentFee:99,patientsAtInception:10,growthRateMonths1to6:12,growthRateMonths7to12:14,growthRateYear2Plus:12,enableAttrition:!1,enableMaxPanel:!0,maxPatientPanel:500,physicianSalary:0,fhManagementPackage:0,fdNetworkFee:0,revenueSharePercent:0,enableProfitSplit:!1,msoSplit:0,stipendPerMonth:0,rent:3750,marketing:24e3,malpracticeInsurance:8e3,commercialInsurance:1200,softw
41areEmrMonthly:350,softwareRampPrice:90,softwareRampUntilPatients:50,softwareRampMaxMonths:12,duesBoardsSubscriptions:39*12,staffWagesMonthly:4e3,staffStartAtPatients:150,fhLaunchFee:46e3,facilityBuildout:0,securityDeposit:7500,signageBranding:0,officeEquipment:0,medicalEquipment:0,initialInventory:0,legalAccounting:0,startupMarketing:0,furnitureFixtures:0,medicalSuppliesStartup:0,initialStaffTraining:0,tbdFields:["malpracticeInsurance","staffWagesMonthly"],scenarioNotes:"Startup: client paid $46,000 in full to FH (all-in launch package â covers buildout, equipment, signage, legal, and launch marketing). Lease security deposit ($7,500) paid separately to landlord. EMR: SigmaMD selected ($90/mo ramp through month 12 or until 50 patients, then $350/mo). Alternative: Hint Clinical $290/mo (Standard) or $320/mo + $36 per 50 members (Growth). Phone: Spruce $39/user/mo (1 user assumed). Malpractice & staff wages are placeholders â confirm with client."},Mi={...Fe,clientName:"",practiceModel:"independent_dpc",practiceSpecialty:"pediatric",infantPricePerMonth:100,childPricePerMonth:75,adultPricePerMonth:175,seniorPricePerMonth:0,infantWeighting:.15,childWeighting:.6,adultWeighting:.25,seniorWeighting:0,patientsAtInception:20,growthRateMonths1to6:15,growthRateMonths7to12:12,growthRateYear2Plus:10,attritionRate:1.5,maxPatientPanel:450,physicianSalary:0,fhManagementPackage:0,fdNetworkFee:0,revenueSharePercent:0,enableProfitSplit:!1,msoSplit:0,stipendPerMonth:0,rent:2500,marketing:36e3,malpracticeInsurance:8e3,commercialInsurance:1200,internetUtilities:3e3,facilityBuildout:1e4,securityDeposit:5e3,signageBranding:3500,officeEquipment:12e3,medicalEquipment:2e4,initialInventory:5e3,legalAccounting:3500,enableAncillaryRevenue:!0,ancillaryServices:[{name:"ADHD Evaluation Package",pricePerService:400,estimatedMonthlyVolume:4,costPerService:50,enabled:!0},{name:"Autism Diagnostic Package",pricePerService:1600,estimatedMonthlyVolume:2,costPerService:200,enabled:!0},{name:"Sports Physical",pricePerService:200,estimatedMonthlyVolume:8,costPerService:20,enabled:!0},{name:"Lactation Support",pricePerService:300,estimatedMonthlyVolume:3,costPerService:50,enabled:!0},{name:"Circumcision",pricePerService:400,estimatedMonthlyVolume:2,costPerService:75,enabled:!0},{name:"One-off Sick Visit",pricePerService:250,estimatedMonthlyVolume:10,costPerService:25,enabled:!0}]},Ci={...Fe,clientName:"",practiceModel:"independent_dpc",practiceSpecialty:"general",infantPricePerMonth:0,childPricePerMonth:100,adultPricePerMonth:175,seniorPricePerMonth:200,infantWeighting:0,childWeighting:.15,adultWeighting:.7,seniorWeighting:.15,patientsAtInception:25,growthRateMonths1to6:18,growthRateMonths7to12:15,growthRateYear2Plus:12,attritionRate:2,maxPatientPanel:600,physicianSalary:0,fhManagementPackage:0,fdNetworkFee:0,revenueSharePercent:0,enableProfitSplit:!1,msoSplit:0,stipendPerMonth:0,rent:2500,marketing:42e3,malpracticeInsurance:1e4,commercialInsurance:1200,internetUtilities:3e3,facilityBuildout:8e3,securityDeposit:5e3,signageBranding:3e3,officeEquipment:12e3,medicalEquipment:18e3,initialInventory:4e3,legalAccounting:3500,enableAncillaryRevenue:!0,ancillaryServices:[{name:"Annual Physical",pricePerService:150,estimatedMonthlyVolume:8,costPerService:20,enabled:!0},{name:"Minor Procedure",pricePerService:200,estimatedMonthlyVolume:4,costPerService:40,enabled:!0},{name:"Sports Physical",pricePerService:150,estimatedMonthlyVolume:5,costPerService:15,enabled:!0},{name:"Chronic Care Management",pricePerService:100,estimatedMonthlyVolume:10,costPerService:15,enabled:!0}]},ki={...Fe,clientName:"",practiceModel:"independent_dpc",practiceSpecialty:"family_medicine",infantPricePerMonth:100,childPricePerMonth:75,adultPricePerMonth:175,seniorPricePerMonth:225,infantWeighting:.05,childWeighting:.2,adultWeighting:.55,seniorWeighting:.2,patientsAtInception:30,growthRateMonths1to6:20,growthRateMonths7to12:15,growthRateYear2Plus:12,attritionRate:1.8,maxPatientPanel:550,physicianSalary:0,fhManagementPackage:0,fdNetworkFee:0,revenueSharePercent:0,enableProfitSplit:!1,msoSplit:0,stipendPerMonth:0,rent:2800,marketing:4e4,malpracticeInsurance:12e3,commercialInsurance:1400,internetUtilities:3e3,facilityBuildout:1e4,securityDeposit:5600,signageBranding:3e3,officeEquipment:14e3,medicalEquipment:22e3,initialInventory:5e3,legalAccounting:4e3,enableAncillaryRevenue:!0,ancillaryServices:[{name:"Annual Physical",pricePerService:150,estimatedMonthlyVolume:10,costPerService:20,enabled:!0},{name:"Well Child Visit",pricePerService:125,estimatedMonthlyVolume:6,costPerService:15,enabled:!0},{name:"Sports Physical",pricePerService:150,estimatedMonthlyVolume:5,costPerService:15,enabled:!0},{name:"Minor Procedure",pricePerService:200,estimatedMonthlyVolume:4,costPerService:40,enabled:!0},{name:"Chronic Care Management",pricePerService:100,estimatedMonthlyVolume:12,costPerService:15,enabled:!0}]},Ri={...Fe,clientName:"",practiceModel:"independent_dpc",practiceSpecialty:"internal_medicine",infantPricePerMonth:0,childPricePerMonth:0,adultPricePerMonth:200,seniorPricePerMonth:275,infantWeighting:0,childWeighting:0,adultWeighting:.65,seniorWeighting:.35,patientsAtInception:20,growthRateMonths1to6:12,growthRateMonths7to12:10,growthRateYear2Plus:8,attritionRate:2.5,maxPatientPanel:500,physicianSalary:0,fhManagementPackage:0,fdNetworkFee:0,revenueSharePercent:0,enableProfitSplit:!1,msoSplit:0,stipendPerMonth:0,rent:3e3,marketing:48e3,malpracticeInsurance:14e3,commercialInsurance:1500,internetUtilities:3200,facilityBuildout:12e3,securityDeposit:6e3,signageBranding:2500,officeEquipment:15e3,medicalEquipment:3e4,initialInventory:6e3,legalAccounting:4e3,enableAncillaryRevenue:!0,ancillaryServices:[{name:"Comprehensive Physical",pricePerService:250,estimatedMonthlyVolume:8,costPerService:30,enabled:!0},{name:"Chronic Care Management",pricePerService:125,estimatedMonthlyVolume:15,costPerService:20,enabled:!0},{name:"EKG/Cardiac Screen",pricePerService:150,estimatedMonthlyVolume:6,costPerService:25,enabled:!0},{name:"Minor Procedure",pricePerService:250,estimatedMonthlyVolume:4,costPerService:50,enabled:!0},{name:"Medication Management",pricePerService:100,estimatedMonthlyVolume:10,costPerService:15,enabled:!0}]},$i=[{id:"blank",name:"Blank Template",description:"Start fresh with default values",specialty:"Any",assumptions:Fe},{id:"pediatric",name:"Pediatric Practice",description:"Focused on children and families with specialty services",specialty:"Pediatric",assumptions:Mi},{id:"general",name:"General DPC",description:"Adult-focused primary care practice",specialty:"General",assumptions:Ci},{id:"family",name:"Family Medicine",description:"Mixed practice serving all ages",specialty:"Family Medicine",assumptions:ki},{id:"internal",name:"Internal Medicine",description:"Adult-only with complex care focus",specialty:"Internal Medicine",assumptions:Ri},{id:"sage-dpc",name:"SAGE Direct Primary Care",description:"Pre-seeded scenario â Dr. Shadmon (2-tier pricing, SigmaMD ramp, $3,750 lease)",specialty:"Featured",assumptions:Pi}],hs=t=>$i.find(x=>x.id===t),aa=[{value:"general",label:"General DPC",icon:dt,presetId:"general",description:"Adult-focused primary care"},{value:"pediatric",label:"Pediatric",icon:Es,presetId:"pediatric",description:"Children ages 0-17"},{value:"family",label:"Family Medicine",icon:Qe,presetId:"family",description:"All ages, whole family"},{value:"internal",label:"Internal Medicine",icon:js,presetId:"internal",description:"Adult medicine 18+"}],Ai=t=>({pediatric:"pediatric",general:"general",family:"family_medicine",internal:"internal_medicine"})[t];function Ei({session:t,onUpdateSession:x,onClearSession:s,onStartWithTemplate:i,onStartWithAI:l,onStartWithSpreadsheet:u,onStartWithSaved:r,savedProjectionsCount:d}){var W;const[M,b]=F.useState(()=>t.zipCode?Lt(t.zipCode):null),[c,p]=F.useState(()=>t.zipCode?Yt(t.zipCode):""),E=S=>{x({zipCode:S}),S.length>=3?(b(Lt(S)),p(Yt(S))):(b(null),p(""))},g=S=>{x({specialty:S,lastPresetUsed:void 0,partialAssumptions:void 0})},O=S=>{const n=t.specialty,X=t.clientName,y=t.zipCode,_=aa.find(T=>T.value===n),w=(_==null?void 0:_.presetId)||"general",h=hs(w);if(S==="template"&&h){const T={...h.assumptions,clientName:X,zipCode:y,practiceSpecialty:Ai(n)};x({lastPresetUsed:w}),i(T)}else S==="ai"?l({clientName:X,zipCode:y,specialty:n}):S==="spreadsheet"?u():S==="saved"&&r()},v=t.clientName.trim()&&t.zipCode.length>=5;return e.jsxs("div",{className:"max-w-3xl mx-auto animate-fade-in",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center p-3 rounded-2xl bg-gradient-to-br from-primary to-primary/70 mb-4 shadow-lg",children:e.jsx(hn,{className:"h-8 w-8 text-primary-foreground"})}),e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-2",children:"Financial Projections"}),e.jsx("p",{className:"text-muted-foreground",children:"Build your practice budget in minutes"})]}),e.jsx(me,{className:"shadow-lg",children:e.jsxs(le,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"clientName",children:"Practice Name"}),e.jsx(Me,{id:"clientName",placeholder:"e.g., Sunrise Family Medicine",value:t.clientName,onChange:S=>x({clientName:S.target.value}),className:"h-11"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"zipCode",children:"ZIP Co
41de"}),e.jsxs("div",{className:"relative",children:[e.jsx(vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Me,{id:"zipCode",placeholder:"e.g., 46032",maxLength:5,value:t.zipCode,onChange:S=>E(S.target.value.replace(/\D/g,"")),className:"pl-9 h-11"})]}),M&&c&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pe,{variant:"outline",className:"text-xs",children:M.label}),c]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Se,{children:"Practice Type"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:aa.map(S=>{const n=S.icon,X=t.specialty===S.value;return e.jsxs("button",{type:"button",onClick:()=>g(S.value),className:de("flex flex-col items-center gap-2 p-4 rounded-xl border-2 transition-all text-center",X?"border-primary bg-primary/5 ring-2 ring-primary/20":"border-transparent bg-muted/50 hover:border-muted-foreground/20 hover:bg-muted"),children:[e.jsx("div",{className:de("p-2.5 rounded-xl transition-colors",X?"bg-primary text-primary-foreground":"bg-muted-foreground/10 text-muted-foreground"),children:e.jsx(n,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:de("font-medium text-sm",X&&"text-primary"),children:S.label}),e.jsx("p",{className:"text-xs text-muted-foreground hidden sm:block",children:S.description})]})]},S.value)})})]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("div",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-3 text-muted-foreground",children:"Choose how to start"})})]}),e.jsxs("div",{className:de("grid gap-3 sm:grid-cols-2 transition-opacity",!v&&"opacity-50 pointer-events-none"),children:[e.jsxs("button",{onClick:()=>O("template"),disabled:!v,className:"flex items-center gap-4 p-4 rounded-xl border-2 border-primary bg-primary/5 hover:bg-primary/10 transition-all text-left group",children:[e.jsx("div",{className:"p-3 rounded-xl bg-primary text-primary-foreground",children:e.jsx(Gt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:["Use Template",e.jsx(lt,{className:"h-4 w-4 opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Pre-filled with ",(W=aa.find(S=>S.value===t.specialty))==null?void 0:W.label," defaults"]})]})]}),e.jsxs("button",{onClick:()=>O("ai"),disabled:!v,className:"flex items-center gap-4 p-4 rounded-xl border-2 border-transparent bg-muted/50 hover:border-primary/30 hover:bg-muted transition-all text-left group",children:[e.jsx("div",{className:"p-3 rounded-xl bg-gradient-to-br from-violet-500 to-purple-600 text-white",children:e.jsx(Ve,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:["AI-Guided Setup",e.jsx(lt,{className:"h-4 w-4 opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Answer a few questions"})]})]}),d>0&&e.jsxs("button",{onClick:()=>O("saved"),disabled:!v,className:"flex items-center gap-4 p-4 rounded-xl border-2 border-transparent bg-muted/50 hover:border-primary/30 hover:bg-muted transition-all text-left group",children:[e.jsx("div",{className:"p-3 rounded-xl bg-warning text-white",children:e.jsx(zt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:["Load Saved",e.jsx(pe,{variant:"secondary",className:"ml-1",children:d}),e.jsx(lt,{className:"h-4 w-4 opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Continue previous work"})]})]})]}),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"Enter practice name and ZIP c
41ode to continue"})]})}),e.jsx(me,{className:"mt-6 border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Ve,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-semibold",children:"Featured Scenarios"}),e.jsx(pe,{variant:"secondary",className:"text-xs",children:"Pre-seeded"})]}),e.jsxs("button",{type:"button",onClick:()=>{const S=hs("sage-dpc");S&&i(S.assumptions)},className:"w-full flex items-center gap-4 p-3 rounded-lg border bg-card hover:border-primary/40 hover:bg-primary/5 transition-all text-left group",children:[e.jsx("div",{className:"p-2.5 rounded-lg bg-primary/10 text-primary",children:e.jsx(dt,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm flex items-center gap-2",children:["SAGE Direct Primary Care",e.jsx(lt,{className:"h-3.5 w-3.5 opacity-0 -translate-x-2 group-hover:opacity-100 group-hover:translate-x-0 transition-all"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Dr. Shadmon · 2-tier pricing ($175 / $225) · SigmaMD ramp · $3,750 lease"})]})]})]})}),(t.clientName||t.zipCode)&&e.jsx("div",{className:"text-center mt-6",children:e.jsxs(V,{variant:"ghost",size:"sm",onClick:s,className:"gap-2 text-muted-foreground",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Start Fresh"]})})]})}function Dt({icon:t,title:x,summary:s,isComplete:i,badge:l,children:u,detailsContent:r,defaultOpen:d=!1}){const[M,b]=F.useState(!1),[c,p]=F.useState(d);return e.jsx(ts,{open:c,onOpenChange:p,children:e.jsxs(me,{className:de("transition-all duration-200",c&&"ring-1 ring-primary/20"),children:[e.jsx(as,{asChild:!0,children:e.jsx(le,{className:"p-4 cursor-pointer hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[i?e.jsx("div",{className:"p-2 rounded-lg bg-success/10 dark:bg-success",children:e.jsx(va,{className:"h-5 w-5 text-success"})}):e.jsx("div",{className:"p-2 rounded-lg bg-primary/10",children:t}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:x}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[l&&e.jsx(pe,{variant:"secondary",className:"font-semibold",children:l}),e.jsx(ia,{className:de("h-5 w-5 text-muted-foreground transition-transform",c&&"rotate-180")})]})]})})}),e.jsx(ss,{children:e.jsx(le,{className:"pt-0 pb-4 px-4",children:e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[u,r&&e.jsxs(ts,{open:M,onOpenChange:b,children:[e.jsx(as,{asChild:!0,children:e.jsxs(V,{type:"button",variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground w-full justify-start",children:[e.jsx(ys,{className:"h-4 w-4"}),M?"Hide":"Show"," Advanced Options",e.jsx(ia,{className:de("h-4 w-4 ml-auto transition-transform",M&&"rotate-180")})]})}),e.jsx(ss,{className:"pt-4",children:r})]})]})})})]})})}const us=[{id:"pediatric_heavy",name:"Pediatric-Heavy",description:"Focused on children and families (70% under 18)",infantWeighting:.15,childWeighting:.6,adultWeighting:.25,seniorWeighting:0,compatibleSpecialties:["pediatric","family_medicine"]},{id:"geriatric_focused",name:"Geriatric-Focused",description:"Senior-heavy panel (65% ages 65+)",infantWeighting:0,childWeighting:0,adultWeighting:.35,seniorWeighting:.65,compatibleSpecialties:["internal_medicine","general","family_medicine"]},{id:"family_balanced",name:"Family Medicine Balanced",description:"Diverse age mix across all demographics",infantWeighting:.05,childWeighting:.2,adultWeighting:.5,seniorWeighting:.25,compatibleSpecialties:["family_medicine"]},{id:"adult_primary",name:"Adult Primary Care",description:"Working-age adults with minimal pediatric",infantWeighting:0,childWeighting:0,adultWeighting:.8,seniorWeighting:.2,compatibleSpecialties:["internal_medicine","general","family_medicine"]}];function Ii(t="New tier"){return{id:`tier-${Math.random().toString(36).slice(2,9)}`,label:t,pricePerMonth:0,weighting:0}}function Fi({assumptions:t,onUpdate:x}){const s=t.customTiers||[],i=s.reduce((c,p)=>c+(p.pricePerMonth||0)*(p.weighting||0),0),l=s.reduce((c,p)=>c+(p.weighting||0),0),u=Math.abs(l-1)<.01,r=c=>x({customTiers:c}),d=(c,p)=>{const E=s.map((g,O)=>O===c?{...g,...p}:g);r(E)},M=()=>r([...s,Ii(`Tier ${s.length+1}`)]),b=c=>r(s.filter((p,E)=>E!==c));return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-medium",children:"Custom Pricing Tiers"}),e.jsxs(V,{type:"button",variant:"outline",size:"sm",onClick:M,className:"gap-1",children:[e.jsx(gs,{className:"h-3 w-3"}),"Add Tier"]})]}),e.jsxs("div",{className:"space-y-2",children:[s.map((c,p)=>e.jsxs("div",{className:"grid grid-cols-[1fr_110px_90px_36px] gap-2 items-center p-2 rounded-lg bg-muted/40",children:[e.jsx(Me,{value:c.label,onChange:E=>d(p,{label:E.target.value}),placeholder:"e.g. Ages 19-44",className:"h-9 text-sm"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"$"}),e.jsx(Me,{type:"number",value:c.pricePerMonth||"",onChange:E=>d(p,{pricePerMonth:Number(E.target.value)}),placeholder:"Price",className:"h-9 text-sm pl-5"})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Me,{type:"number",value:Math.round((c.weighting||0)*100)||"",onChange:E=>d(p,{weighting:Math.max(0,Math.min(100,Number(E.target.value)))/100}),placeholder:"Mix",className:"h-9 text-sm pr-6",max:100,min:0}),e.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"%"})]}),e.jsx(V,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>b(p),disabled:s.length<=1,children:e.jsx(ja,{className:"h-3.5 w-3.5"})})]},c.id)),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground italic px-2",children:"No tiers yet â add one to define pricing."})]}),e.jsxs("div",{className:de("flex items-center justify-between p-3 rounded-lg border",u?"bg-success/10 border-success/20":"bg-destructive/10 border-destructive/20"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Blended Price"}),e.jsxs("p",{className:"text-xl font-bold",children:[A(i),"/mo"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Mix"}),e.jsxs(pe,{variant:u?"default":"destructive",children:[Math.round(l*100),"%"]})]})]})]})}const Ot={infant:"bg-destructive",child:"bg-info",adult:"bg-success",senior:"bg-accent"};function Ti({assumptions:t,onUpdate:x}){const s=t.practiceSpecialty||"general",i=s==="internal_medicine"||s==="general",l=s==="pediatric",u=t.pricingMode||"four_tier",r=[{value:"four_tier",label:"4 Age Tiers"},{value:"two_tier",label:"Custom Tiers"},{value:"flat",label:"Single Price"}],d=h=>{h==="two_tier"&&!(t.customTiers&&t.customTiers.length)?x({pricingMode:h,customTiers:[{id:"tier-a",label:"Tier A",pricePerMonth:175,weighting:.6},{id:"tier-b",label:"Tier B",pricePerMonth:225,weighting:.4}]}):h==="flat"&&!t.flatPricePerMonth?x({pricingMode:h,flatPricePerMonth:175}):x({pricingMode:h})},M=e.jsx("div",{className:"flex flex-wrap gap-1 p-1 bg-muted/50 rounded-lg w-fit",children:r.map(h=>e.jsx("button",{type:"button",onClick:()=>
41d(h.value),className:de("text-xs px-3 py-1.5 rounded-md transition-colors",u===h.value?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"),children:h.label},h.value))});if(u==="two_tier")return e.jsxs("div",{className:"space-y-4",children:[M,e.jsx(Fi,{assumptions:t,onUpdate:x})]});if(u==="flat")return e.jsxs("div",{className:"space-y-4",children:[M,e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Membership Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-2 top-1/2 -translate-y-1/2 text-sm text-muted-foreground",children:"$"}),e.jsx(Me,{type:"number",value:t.flatPricePerMonth||"",onChange:h=>x({flatPricePerMonth:Number(h.target.value)}),className:"w-32 pl-5"})]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"/month per patient"})]})]});const b=us.filter(h=>!h.compatibleSpecialties||h.compatibleSpecialties.includes(s)),c=F.useMemo(()=>i?t.adultPricePerMonth*t.adultWeighting+t.seniorPricePerMonth*t.seniorWeighting:l?t.infantPricePerMonth*t.infantWeighting+t.childPricePerMonth*t.childWeighting+t.adultPricePerMonth*t.adultWeighting:t.infantPricePerMonth*t.infantWeighting+t.childPricePerMonth*t.childWeighting+t.adultPricePerMonth*t.adultWeighting+t.seniorPricePerMonth*t.seniorWeighting,[t,i,l]),p=F.useMemo(()=>i?t.adultWeighting+t.seniorWeighting:l?t.infantWeighting+t.childWeighting+t.adultWeighting:t.infantWeighting+t.childWeighting+t.adultWeighting+t.seniorWeighting,[t,i,l]),E=Math.abs(p-1)<.01,g=F.useMemo(()=>[{key:"infant",label:l?"Infant (0-24mo)":"Infant (0-2)",price:t.infantPricePerMonth,weight:t.infantWeighting,color:Ot.infant,hidden:i},{key:"child",label:l?"Toddler (2-6yr)":"Child (3-17)",price:t.childPricePerMonth,weight:t.childWeighting,color:Ot.child,hidden:i},{key:"adult",label:l?"School-Age (7-17)":"Adult (18-64)",price:t.adultPricePerMonth,weight:t.adultWeighting,color:Ot.adult,hidden:!1},{key:"senior",label:"Senior (65+)",price:t.seniorPricePerMonth,weight:t.seniorWeighting,color:Ot.senior,hidden:l}].filter(T=>!T.hidden),[t,i,l]),[O,v]=F.useState(null),[W,S]=F.useState(""),n=(h,T)=>{const U=`${h}Weighting`;x({[U]:T/100})},X=(h,T)=>{v(h),S(String(T))},y=h=>{const T=`${h}PricePerMonth`,U=Number(W);!isNaN(U)&&U>=0&&x({[T]:U}),v(null),S("")},_=(h,T)=>{h.key==="Enter"?y(T):h.key==="Escape"&&(v(null),S(""))},w=h=>{const T=us.find(U=>U.id===h);T&&x({infantWeighting:T.infantWeighting,childWeighting:T.childWeighting,adultWeighting:T.adultWeighting,seniorWeighting:T.seniorWeighting})};return e.jsxs("div",{className:"space-y-4",children:[M,e.jsx("div",{className:"flex flex-wrap gap-2",children:b.map(h=>e.jsxs(V,{type:"button",variant:"outline",size:"sm",className:"text-xs gap-1.5",onClick:()=>w(h.id),children:[e.jsx(un,{className:"h-3 w-3"}),h.name]},h.id))}),e.jsx("div",{className:"h-4 rounded-full overflow-hidden flex bg-muted",children:g.map(h=>e.jsx("div",{className:de(h.color,"transition-all duration-300"),style:{width:`${h.weight*100}%`},title:`${h.label}: ${Math.round(h.weight*100)}%`},h.key))}),e.jsx("div",{className:"space-y-4",children:g.map(h=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:de("w-3 h-3 rounded-full",h.color)}),e.jsx("span",{className:"text-sm font-medium",children:h.label})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[O===h.key?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"$"}),e.jsx(Me,{type:"number",value:W,onChange:T=>S(T.target.value),onKeyDown:T=>_(T,h.key),onBlur:()=>y(h.key),className:"w-20 h-7 text-xs",autoFocus:!0}),e.jsx(V,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>y(h.key),children:e.jsx(va,{className:"h-3 w-3"})})]}):e.jsxs(pe,{variant:"outline",className:"text-xs cursor-pointer hover:bg-muted group",onClick:()=>X(h.key,h.price),children:[A(h.price),"/mo",e.jsx(Kn,{className:"h-2.5 w-2.5 ml-1 opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsxs("span",{className:"text-sm font-semibold w-12 text-right",children:[Math.round(h.weight*100),"%"]})]})]}),e.jsx(ut,{value:[h.weight*100],onValueChange:([T])=>n(h.key,T),max:100,step:1,className:"w-full"})]},h.key))}),e.jsxs("div",{className:de("flex items-center justify-between p-3 rounded-lg border",E?"bg-success/10 border-success/20 dark:bg-success dar
41k:border-success":"bg-destructive/10 border-destructive/20 dark:bg-destructive dark:border-destructive"),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Blended Price"}),e.jsxs("p",{className:"text-2xl font-bold",children:[A(c),"/mo"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Mix"}),e.jsxs(pe,{variant:E?"default":"destructive",children:[Math.round(p*100),"%"]})]})]})]})}function Di({assumptions:t,className:x}){var c,p,E,g,O,v,W,S,n,X,y,_,w;const s=F.useMemo(()=>{try{return yt(t)}catch{return null}},[t]),i=mt(t),l=((p=(c=s==null?void 0:s.yearlySummaries)==null?void 0:c[2])==null?void 0:p.totalRevenue)||0;(g=(E=s==null?void 0:s.yearlySummaries)==null?void 0:E[2])!=null&&g.netIncome;const u=((v=(O=s==null?void 0:s.yearlySummaries)==null?void 0:O[2])==null?void 0:v.endingPatients)||0,r=s==null?void 0:s.breakEvenMonth,d=(s==null?void 0:s.peakCapitalDeployment)||0,M=((S=(W=s==null?void 0:s.yearlySummaries)==null?void 0:W[2])==null?void 0:S.physicianTotalComp)||0,b=((X=(n=s==null?void 0:s.yearlySummaries)==null?void 0:n[0])==null?void 0:X.totalRevenue)||0;return(_=(y=s==null?void 0:s.yearlySummaries)==null?void 0:y[0])!=null&&_.netIncome,e.jsxs("div",{className:de("space-y-4",x),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-lg flex items-center gap-2",children:[e.jsx(Je,{className:"h-5 w-5 text-primary"}),"Live Preview"]}),e.jsx(pe,{variant:"secondary",className:"text-xs",children:"Auto-updating"})]}),e.jsx(me,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(le,{className:"p-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Average Monthly Price"}),e.jsx("p",{className:"text-3xl font-bold text-primary",children:A(i)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"per patient/month"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Bt,{label:"Year 3 Revenue",value:A(l),trend:l>b?"up":"neutral"}),e.jsx(Bt,{label:"Physician Comp",value:A(M),subtext:"salary + bonus",trend:"up"}),e.jsx(Bt,{label:"Break-Even",value:r?`Month ${r}`:"TBD",trend:r&&r<18?"up":"neutral"}),e.jsx(Bt,{label:"Peak Capital",value:A(d),subtext:"required",trend:"neutral"})]}),e.jsx(me,{className:"bg-muted/30",children:e.jsxs(le,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Year 3 Patients"}),e.jsx("p",{className:"text-2xl font-bold",children:u})]}),e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(Qe,{className:"h-6 w-6 text-primary"})})]}),t.enableMaxPanel&&t.maxPatientPanel&&e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all duration-500",style:{width:`${Math.min(u/t.maxPatientPanel*100,100)}%`}})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Math.round(u/t.maxPatientPanel*100),"% of max panel"]})]})]})}),e.jsx(me,{children:e.jsxs(le,{className:"p-4",children:[e.jsx("h4",{className:"text-sm font-medium mb-3",children:"Revenue by Year"}),e.jsx("div",{className:"space-y-2",children:(w=s==null?void 0:s.yearlySummaries)==null?void 0:w.map((h,T)=>{var U;return e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Year ",h.year]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:A(h.totalRevenue)}),T>0&&((U=s==null?void 0:s.yearlySummaries)==null?void 0:U[T-1])&&e.jsx(pe,{variant:h.totalRevenue>s.yearlySummaries[T-1].totalRevenue?"default":"secondary",className:"text-xs px-1.5",children:h.totalRevenue>s.yearlySummaries[T-1].totalRevenue?e.jsx($s,{className:"h-3 w-3"}):e.jsx(As,{className:"h-3 w-3"})})]})]},T)})})]})})]})}function Bt({label:t,value:x,subtext:s,trend:i}){return e.jsx(me,{className:"bg-muted/30",children:e.jsxs(le,{className:"p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:t}),e.jsxs("p",{className:"text-lg font-semibold flex items-center gap-1",children:[x,i==="up"&&e.jsx($s,{className:"h-3 w-3 text-success"}),i==="down"&&e.jsx(As,{className:"h-3 w-3 text-destructive"})]}),s&&e.jsx("p",{className:"text-xs text-muted-foreground",children:s})]})})}function we({label:t,tooltip:x,...s}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Se,{htmlFor:s.id,className:"text-sm",children:t}),x&&e.jsxs(xn,{children:[e.jsx(pn,{asChild:!0,children:e.jsx(gn,{className:"h-3.5 w-3.5 text-muted-foreground cursor-help"})}),e.jsx(fn,{side:"top",className:"max-w-xs",children:e.jsx("p",{className:"text-xs",children:x})})]})]}),e.jsx(Me,{...s})]})}function Oi({initialValues:t,onSubmit:x,onBack:s,onAssumptionsChange:i}){var w;const[l,u]=F.useState(t||Fe),[r,d]=F.useState(null),[M,b]=F.useState("");F.useEffect(()=>{l.zipCode&&l.zipCode.length>=3&&(d(Lt(l.zipCode)),b(Yt(l.zipCode)))},[]),F.useEffect(()=>{i==null||i(l)},[l,i]);const c=F.useCallback((h,T)=>{u(U=>({...U,[h]:T}))},[]),p=F.useCallback(h=>{u(T=>({...T,...h}))},[]),E=F.useCallback(h=>{const T=h.replace(/\D/g,"").slice(0,5);if(c("zipCode",T),T.length>=3){const U=Lt(T);if(d(U),b(Yt(T)),T.length===5){const j=wi(U.level),R=Math.round(2500*j.rent);u(H=>({...H,zipCode:T,adultPricePerMonth:Math.round(175*j.pricing),childPricePerMonth:Math.round(100*j.pricing),rent:R,securityDeposit:R*2,malpracticeInsurance:Math.round(1e4*j.insurance),commercialInsurance:Math.round(1200*j.insurance),marketing:Math.round(4e4*j.marketing),internetUtilities:Math.round(3e3*j.utilities),facilityBuildout:Math.round(1e4*j.buildout),legalAccounting:Math.round(3500*j.professional)}))}}else d(null),b("")},[c]),g=mt(l),O=l.practiceSpecialty==="internal_medicine"||l.practiceSpecialty==="general",v=F.useMemo(()=>O?l.adultWeighting+l.seniorWeighting:l.practiceSpecialty==="pediatric"?l.infantWeighting+l.childWeighting+l.adultWeighting:l.infantWeighting+l.childWeighting+l.adultWeighting+l.seniorWeighting,[l,O]),W=g>0&&Math.abs(v-1)<.01,S=(l.growthRateMonths1to6||0)>0,n=(l.rent||0)>0||(l.fhManagementPackage||0)>0,X=(l.rent||0)+(l.malpracticeInsurance||0)/12+(l.fhManagementPackage||0)+(l.softwareEmrMonthly||0),y=(l.facilityBuildout||0)+(l.securityDeposit||0)+(l.medicalEquipment||0)+(l.legalAccounting||0),_=h=>{h.preventDefault(),x(l)};return e.jsxs("form",{onSubmit:_,className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[1fr_380px] gap-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx(me,{children:e.jsx(le,{className:"p-4",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsx(we,{id:"clientName",label:"Practice Name",value:l.clientName,onChange:h=>c("clientName",h.target.value),placeholder:"e.g., Sunrise Family Medicine"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Se,{htmlFor:"zipCode",className:"text-sm",children:"ZIP Co
41de"}),e.jsxs("div",{className:"relative",children:[e.jsx(vs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(Me,{id:"zipCode",value:l.zipCode||"",onChange:h=>E(h.target.value),placeholder:"e.g., 46032",className:"pl-9",maxLength:5})]}),r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pe,{variant:r.level==="high"?"destructive":r.level==="low"?"outline":"secondary",className:"text-xs",children:r.label}),M&&e.jsx("span",{className:"text-xs text-muted-foreground",children:M})]})]}),e.jsx(we,{id:"startupDate",label:"Launch Date",type:"date",value:l.startupDate,onChange:h=>c("startupDate",h.target.value)})]})})}),e.jsxs(Dt,{icon:e.jsx(_t,{className:"h-5 w-5 text-primary"}),title:"Membership Pricing",summary:`${A(g)}/mo blended ⢠${Math.round(v*100)}% mix`,isComplete:W,badge:A(g),defaultOpen:!0,children:[e.jsx(Ti,{assumptions:l,onUpdate:p}),e.jsx("div",{className:"pt-2",children:e.jsx(we,{id:"enrollmentFee",label:"Enrollment Fee",type:"number",tooltip:"One-time fee for new patients",value:l.enrollmentFee||"",onChange:h=>c("enrollmentFee",Number(h.target.value)),className:"max-w-[200px]"})})]}),e.jsxs(Dt,{icon:e.jsx(Qe,{className:"h-5 w-5 text-primary"}),title:"Patient Growth",summary:`${l.growthRateMonths1to6||0}/mo (M1-6) â ${l.growthRateMonths7to12||0}/mo (M7-12)`,isComplete:S,badge:`${l.maxPatientPanel||600} max`,children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsx(we,{id:"patientsAtInception",label:"Pre-Enrolled",type:"number",tooltip:"Patients signed up before launch",value:l.patientsAtInception||"",onChange:h=>c("patientsAtInception",Number(h.target.value))}),e.jsx(we,{id:"growthRateMonths1to6",label:"Mo 1-6",type:"number",tooltip:"New patients per month",value:l.growthRateMonths1to6||"",onChange:h=>c("growthRateMonths1to6",Number(h.target.value))}),e.jsx(we,{id:"growthRateMonths7to12",label:"Mo 7-12",type:"number",value:l.growthRateMonths7to12||"",onChange:h=>c("growthRateMonths7to12",Number(h.target.value))}),e.jsx(we,{id:"growthRateYear2Plus",label:"Year 2+",type:"number",value:l.growthRateYear2Plus||"",onChange:h=>c("growthRateYear2Plus",Number(h.target.value))})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 pt-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{id:"enableMaxPanel",checked:l.enableMaxPanel,onCheckedChange:h=>c("enableMaxPanel",h)}),e.jsxs(Se,{htmlFor:"enableMaxPanel",className:"text-sm",children:["Max Panel: ",l.maxPatientPanel||600]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{id:"enableAttrition",checked:l.enableAttrition,onCheckedChange:h=>c("enableAttrition",h)}),e.jsxs(Se,{htmlFor:"enableAttrition",className:"text-sm",children:["Attrition: ",l.attritionRate||1.5,"%"]})]})]})]}),e.jsx(Dt,{icon:e.jsx(Rs,{className:"h-5 w-5 text-primary"}),title:"Costs & Expenses",summary:`~${A(X)}/mo operating ⢠${A(y)} startup`,isComplete:n,badge:A(y),detailsContent:e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(we,{id:"malpracticeInsurance",label:"Malpractice (Annual)",type:"number",value:l.malpracticeInsurance||"",onChange:h=>c("malpracticeInsurance",Number(h.target.value))}),e.jsx(we,{id:"marketing",label:"Marketing (Annual)",type:"number",value:l.marketing||"",onChange:h=>c("marketing",Number(h.target.value))}),e.jsx(we,{id:"facilityBuildout",label:"Facility Buildout",type:"number",value:l.facilityBuildout||"",onChange:h=>c("facilityBuildout",Number(h.target.value))}),e.jsx(we,{id:"medicalEquipment",label:"Medical Equipment",type:"number",value:l.medicalEquipment||"",onChange:h=>c("medicalEquipment",Number(h.target.value))}),e.jsx(we,{id:"legalAccounting",label:"Legal/Accounting",type:"number",value:l.legalAccounting||"",onChange:h=>c("legalAccounting",Number(h.target.value))}),e.jsx(we,{id:"staffWagesMonthly",label:"Staff Wages (Monthly)",type:"number",value:l.staffWagesMonthly||"",onChange:h=>c("staffWagesMonthly",Number(h.target.value))})]}),children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsx(we,{id:"rent",label:"Monthly Rent",type:"number",tooltip:"Office space rent per month",value:l.rent||"",onChange:h=>c("rent",Number(h.target.value))}),e.jsx(we,{id:"fhManagementPackage",label:"FH Operations (Monthly)",type:"number",tooltip:"Freedom Healthworks monthly operations package fee",value:l.fhManagementPackage||"",onChange:h=>c("fhManagementPackage",Number(h.target.value))}),e.jsx(we,{id:"softwareEmrMonthly",label:"Software/EMR (Monthly)",type:"number",tooltip:"Monthly EMR and software subscriptions",value:l.softwareEmrMonthly||"",onChange:h=>c("softwareEmrMonthly",Number(h.target.value))}),e.jsx(we,{id:"physicianSalary",label:"Physician Salary",type:"number",tooltip:"Annual base salary",value:l.physicianSalary||"",onChange:h=>c("physicianSalary",Number(h.target.value))})]})}),e.jsx(Dt,{icon:e.jsx(dt,{className:"h-5 w-5 text-primary"}),title:"Ancillary Services",summary:l.enableAncillaryRevenue?`${((w=l.ancillaryServices)==null?void 0:w.filter(h=>h.enabled).length)||0} services enabled`:"Disabled",isComplete:!0,badge:l.enableAncillaryRevenue?"Active":"Off",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Se,{htmlFor:"enableAncillary",className:"text-sm",children:"Enable Ancillary Revenue"}),e.jsx(Rt,{id:"enableAncillary",checked:l.enableAncillaryRevenue,onCheckedChange:h=>{c("enableAncillaryRevenue",h),h&&(!l.ancillaryServices||l.ancillaryServices.length===0)&&c("ancillaryServices",Ss)}})]}),l.enableAncillaryRevenue&&l.ancillaryServices&&e.jsx("div",{className:"space-y-3 border-t pt-3",children:l.ancillaryServices.map((h,T)=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg bg-muted/50",children:[e.jsx(Rt,{checked:h.enabled,onCheckedChange:U=>{const j=[...l.ancillaryServices];j[T]={...h,enabled:U},c("ancillaryServices",j)}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:h.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[A(h.pricePerService)," per service"]})]}),h.enabled&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Me,{type:"number",value:h.estimatedMonthlyVolume||"",onChange:U=>{const j=[...l.ancillaryServices];j[T]={...h,estimatedMonthlyVolume:Number(U.target.value)},c("ancillaryServices",j)},className:"w-16 h-8 text-xs",placeholder:"Vol"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"/mo"})]})]},h.name))})]})}),e.jsxs("div",{className:"flex items-center justify-between pt-4",children:[e.jsx(V,{type:"button",variant:"ghost",onClick:s,children:"â Back"}),e.jsxs(V,{type:"submit",size:"lg",className:"gap-2",children:["View Projections",e.
41jsx(lt,{className:"h-4 w-4"})]})]})]}),e.jsx("div",{className:"hidden lg:block",children:e.jsx("div",{className:"sticky top-4",children:e.jsx(Di,{assumptions:l})})})]}),e.jsx("div",{className:"lg:hidden fixed bottom-4 right-4 z-50",children:e.jsxs(V,{type:"submit",size:"lg",className:"shadow-lg gap-2",children:[e.jsx(Je,{className:"h-4 w-4"}),"View Results"]})})]})}const sa="budgeting-session",Bi=500,Wt={clientName:"",zipCode:"",specialty:"general"};function Wi(){const[t,x]=F.useState(()=>{try{const p=localStorage.getItem(sa);return p?{...Wt,...JSON.parse(p)}:Wt}catch{return Wt}}),s=F.useRef(null),i=F.useRef(!1);F.useEffect(()=>(s.current&&clearTimeout(s.current),s.current=setTimeout(()=>{try{localStorage.setItem(sa,JSON.stringify({...t,lastUpdated:new Date().toISOString()}))}catch{}},Bi),()=>{s.current&&clearTimeout(s.current)}),[t]);const l=F.useCallback(p=>{x(E=>({...E,...p}))},[]),u=F.useCallback((p,E,g)=>{x(O=>({...O,fullAssumptions:p,viewMode:E,cachedResults:g,clientName:p.clientName||O.clientName,zipCode:p.zipCode||O.zipCode}))},[]),r=F.useCallback(()=>t.fullAssumptions&&t.viewMode&&t.viewMode!=="wizard"?(i.current=!0,{assumptions:t.fullAssumptions,viewMode:t.viewMode,results:t.cachedResults,hasState:!0}):{hasState:!1},[t]),d=F.useCallback(()=>{x(Wt),localStorage.removeItem(sa),i.current=!1},[]),M=!!(t.clientName&&t.zipCode&&t.specialty),b=!!(t.fullAssumptions&&t.viewMode&&t.viewMode!=="wizard"),c=i.current;return{session:t,updateSession:l,saveFullState:u,restoreState:r,clearSession:d,hasBasicInfo:M,hasSavedState:b,wasRestored:c}}const Dr=()=>{const[t]=Us(),{user:x}=ga(),{projections:s,loading:i,saveProjection:l,deleteProjection:u}=jn(),{session:r,updateSession:d,saveFullState:M,restoreState:b,clearSession:c,hasSavedState:p}=Wi(),[E,g]=F.useState("wizard"),O=F.useRef(!1),v=t.get("clientId"),W=t.get("name");F.useEffect(()=>{v&&W&&d({clientName:W,linkedClientId:v})},[v,W,d]);const[S,n]=F.useState(null),[X,y]=F.useState(Fe),[_,w]=F.useState(null),[h,T]=F.useState(null),[U,j]=F.useState(!1);F.useEffect(()=>{if(O.current)return;const D=b();D.hasState&&D.assumptions&&D.viewMode&&(O.current=!0,n(D.assumptions),y(D.assumptions),g(D.viewMode),D.results&&T(D.results),ge.success("Restored your previous projection",{duration:2e3}))},[b]),F.useEffect(()=>{S&&E!=="wizard"&&E!=="upload"&&E!=="saved"&&M(S,E,h||void 0)},[S,E,h,M]);const R=()=>{c(),n(null),y(Fe),T(null),g("wizard"),O.current=!1,ge.success("Starting fresh")},H=D=>{n(D);const se=yt(D),fe=ns(se);T({results:se,explanations:fe}),g("comparison")},ee=()=>{g("wizard"),T(null)},z=()=>{S&&y(S),g("form")},C=()=>{S&&g("comparison")},K=()=>{S&&h&&g("projections")},Q=D=>{const se={...Fe,...D,clientName:r.clientName||D.clientName||""};y(se),g("form"),ge.success(`Imported ${Object.keys(D).length} values from spreadsheet`)},G=D=>{const se={...Fe,...D.assumptions,ancillaryServices:D.assumptions.ancillaryServices||Ss};y(se),n(se),g("form"),ge.success(`Loaded "${D.name}"`)},te=D=>{y(D),n(D);const se=yt(D),fe=ns(se);T({results:se,explanations:fe}),g("comparison"),ge.success("Practice setup complete!")},Z=D=>{y(D),g("form"),ge.success("Template loaded - customize the values below")},m=D=>{w(D),g("intake")},Y=()=>{g("upload")},L=()=>{g("saved")};return e.jsx("div",{className:"min-h-dvh bg-background",children:e.jsxs("div",{className:"container max-w-7xl py-6 px-4 sm:px-6 lg:px-8",children:[E==="wizard"&&e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[p?e.jsxs(V,{variant:"ghost",size:"sm",onClick:R,className:"gap-2 text-muted-foreground",children:[e.jsx(Ns,{className:"h-4 w-4"}),"Clear & Start Over"]}):e.jsx("div",{}),x&&s.length>0&&e.jsxs(V,{variant:"outline",size:"sm",onClick:()=>g("saved"),className:"gap-2",children:[e.jsx(zt,{className:"h-4 w-4"}),"Saved (",s.length,")"]})]}),E==="projections"&&h&&S&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs(V,{variant:"ghost",onClick:z,className:"gap-2",children:[e.jsx(pt,{className:"h-4 w-4"}),"Edit Assumptions"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(V,{variant:"outline",onClick:()=>j(!0),className:"gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),"Save"]}),e.jsxs(V,{variant:"outline",onClick:C,className:"gap-2",children:[e.jsx(Zn,{className:"h-4 w-4"}),"Compare"]})]})]}),e.jsx(xi,{results:h.results,explanations:h.explanations,onBack:ee}),e.jsx(ds,{open:U,onOpenChange:j,assumptions:S,initialClientId:r.linkedClientId,onSave:l})]}),E==="comparison"&&S&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs(V,{variant:"ghost",onClick:z,className:"gap-2",children:[e.jsx(pt,{className:"h-4 w-4"}),"Edit Assumptions"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(V,{variant:"outline",onClick:()=>j(!0),className:"gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),"Save"]}),e.jsxs(V,{variant:"outline",onClick:K,className:"gap-2",children:[e.jsx(Je,{className:"h-4 w-4"}),"Detailed View"]}
41)]})]}),e.jsx(gi,{baseAssumptions:S,onBack:ee}),e.jsx(ds,{open:U,onOpenChange:j,assumptions:S,initialClientId:r.linkedClientId,onSave:l})]}),E==="wizard"&&e.jsx(Ei,{session:r,onUpdateSession:d,onClearSession:c,onStartWithTemplate:Z,onStartWithAI:m,onStartWithSpreadsheet:Y,onStartWithSaved:L,savedProjectionsCount:s.length}),E==="form"&&e.jsx(Oi,{initialValues:X,onSubmit:H,onBack:()=>g("wizard"),onAssumptionsChange:D=>n(D)}),E==="upload"&&e.jsx("div",{className:"max-w-2xl mx-auto",children:e.jsx(fi,{onImport:Q,onCancel:()=>g("wizard")})}),E==="saved"&&e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"mb-6",children:e.jsxs(V,{variant:"ghost",onClick:()=>g("wizard"),className:"gap-2",children:[e.jsx(pt,{className:"h-4 w-4"}),"Back"]})}),e.jsx(ji,{projections:s,loading:i,onLoad:G,onDelete:u})]}),E==="intake"&&e.jsx(Ni,{onComplete:te,onCancel:()=>g("wizard"),initialData:_||void 0})]})})};export{Dr as default};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.