1import{c as Ge,r as b,a as Yt,u as qs,j as e,b as ee,L as ge,U as Hs,C as ye,S as Ks,I as le,d as Ea,T as Ws,e as Ia,f as Vs,g as za,h as Ba,i as qa,k as Qs,l as qt,m as Ha,n as Ka,o as Wa,p as Va,D as Ue,q as Ye,s as Qa,t as Ya,v as Ga,w as lt,x as pe,y as Gt,z as Ua,A as Ut,B as Ja,E as Xa,X as Me,F as Jt,G as Za,H as Ys,J as en,K as tn,M as Gs,N as sn,O as an,P as Ht,Q as nn,R as rn,V as ln,W as Xt,Y as Ae,Z as on,_ as cn,$ as dn,a0 as xn,a1 as Zt,a2 as mn,a3 as $t,a4 as un,a5 as pn,a6 as hn,a7 as fn,a8 as Us,a9 as Js,aa as gn,ab as Kt,ac as Xs,ad as yn,ae as bn,af as _n,ag as jn,ah as vn,ai as Zs,aj as ea,ak as Ce,al as Nn,am as cs,an as wn,ao as kn,ap as Sn,aq as Cn,ar as Mn,as as $n,at as Fn,au as An,av as Pn,aw as Rn}from"./index-Df108JlE.js";import{C as Dn,A as Tn,u as ta,S as Ln,a as On,b as En}from"./AiSummaryCard-DTn9Uq8W.js";import{u as De}from"./useModalA11y-B5_bs4oH.js";import{g as In,P as zn,R as Bn,a as qn,F as Hn}from"./RateVariantTooltip-Dtp4XVh_.js";import{C as gt}from"./chevron-right-C5-qd-S8.js";import{c as fe,p as yt,a as Kn,i as Wn,s as Je,b as Vn,d as Qn,e as sa,f as Yn,g as Gn,h as ze,j as Un,k as Jn,l as Xn,m as Zn,n as aa,o as er,q as tr,r as sr,t as ar,u as na,v as nr,w as rr,x as lr,y as ra,z as ir,A as es,B as la,R as or,S as cr,D as ia,C as oa,E as pt,F as dr,L as rt,Z as ca,G as xr,H as mr,J as ur,I as pr,K as ds,M as xs,N as St,P as hr,O as fr,Q as gr,T as yr,U as br,V as _r,W as jr,X as vr,Y as Nr,_ as wr,$ as ht,a0 as Wt,a1 as ms,a2 as kr,a3 as Sr,a4 as Cr,a5 as Mr,a6 as $r,a7 as Fr,a8 as Ar,a9 as Pr,aa as Rr,ab as Dr,ac as Tr,ad as Lr,ae as Or,af as je,ag as de,ah as xe,ai as ce}from"./CartesianChart-CxTC1H5D.js";import{C as Ft,u as Er,a as Ir,b as zr,B as it,c as _e}from"./BarChart-C3zlDDul.js";import{C as he}from"./CartesianGrid-CgHY_Blv.js";import{L as Fe}from"./Legend-DQKG7AK5.js";import{L as oe,a as $e}from"./LineChart-BhL0DOVD.js";import{Q as Br}from"./QueryError-Csi7m0zt.js";import{C as ts}from"./CloseButton-CAKvuKo3.js";import{M as ft}from"./maximize-2-C1hFM99k.js";import{E as da}from"./external-link-BJSx0NF5.js";import{R as ss}from"./ReferenceLine-8H7qsIer.js";import{A as qr,a as Hr}from"./AnalysisRequestModal-Dkb7uKyY.js";import{M as xa}from"./minimize-2-xTu8mWpA.js";import{P as Kr}from"./pin-DbtLnbHO.js";import{S as Wr,a as Vr,b as Qr,N as Yr}from"./serviceLines-DqRkUf9L.js";import{C as ma}from"./circle-alert-DxMkBaLP.js";import{C as Gr}from"./chevron-left-BG1_bPN5.js";import{C as ua}from"./columns-2-Bj6wLKAU.js";import{R as Ur}from"./ReferenceArea-DOXhjVlc.js";const Jr=[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]],pa=Ge("arrow-up-right",Jr);const Xr=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],us=Ge("circle-check",Xr);const Zr=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],el=Ge("ellipsis",Zr);const tl=[["path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4",key:"1slcih"}]],sl=Ge("flame",tl);const al=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]],nl=Ge("history",al);const rl=[["path",{d:"M10 18v-7",key:"wt116b"}],["path",{d:"M11.12 2.198a2 2 0 0 1 1.76.006l7.866 3.847c.476.233.31.949-.22.949H3.474c-.53 0-.695-.716-.22-.949z",key:"1m329m"}],["path",{d:"M14 18v-7",key:"vav6t3"}],["path",{d:"M18 18v-7",key:"aexdmj"}],["path",{d:"M3 22h18",key:"8prr45"}],["path",{d:"M6 18v-7",key:"1ivflk"}]],ll=Ge("landmark",rl);const il=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],ol=Ge("target",il);var ha=t=>t.graphicalItems.polarItems,cl=fe([yt,Kn],Wn),At=fe([ha,Je,cl],Vn),dl=fe([At],Qn),Pt=fe([dl,sa],Yn),xl=fe([Pt,Je,At],Gn);fe([Pt,Je,At],(t,s,a)=>a.length>0?t.flatMap(n=>a.flatMap(r=>{var l,o=ze(n,(l=s.dataKey)!==null&&l!==void 0?l:r.dataKey);return{value:o,errorDomain:[]}}
1)).filter(Boolean):s?.dataKey!=null?t.map(n=>({value:ze(n,s.dataKey),errorDomain:[]})):t.map(n=>({value:n,errorDomain:[]})));var ps=()=>{},ml=fe([Pt,Je,At,Un,yt],Jn),ul=fe([Je,Xn,Zn,ps,ml,ps,aa,yt],er),fa=fe([Je,aa,Pt,xl,tr,yt,ul],sr),pl=fe([fa,ar,na],nr),hl=fe([Je,fa,pl,yt],rr);fe([na,hl],lr);function hs(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);s&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),a.push.apply(a,n)}return a}function fs(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?hs(Object(a),!0).forEach(function(n){fl(t,n,a[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):hs(Object(a)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(a,n))})}return t}function fl(t,s,a){return(s=gl(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function gl(t){var s=yl(t,"string");return typeof s=="symbol"?s:s+""}function yl(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var n=a.call(t,s);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}var bl=(t,s)=>s,as=fe([ha,bl],(t,s)=>t.filter(a=>a.type==="pie").find(a=>a.id===s)),_l=[],ns=(t,s,a)=>a?.length===0?_l:a,ga=fe([sa,as,ns],(t,s,a)=>{var{chartData:n}=t;if(s!=null){var r;if(s?.data!=null&&s.data.length>0?r=s.data:r=n,(!r||!r.length)&&a!=null&&(r=a.map(l=>fs(fs({},s.presentationProps),l.props))),r!=null)return r}}),jl=fe([ga,as,ns],(t,s,a)=>{if(!(t==null||s==null))return t.map((n,r)=>{var l,o=ze(n,s.nameKey,s.name),d;return a!=null&&(l=a[r])!==null&&l!==void 0&&(l=l.props)!==null&&l!==void 0&&l.fill?d=a[r].props.fill:typeof n=="object"&&n!=null&&"fill"in n?d=n.fill:d=s.fill,{value:ra(o,s.dataKey),color:d,payload:n,type:s.legendType}})}),vl=fe([ga,as,ns,ir],(t,s,a,n)=>{if(!(s==null||t==null))return Hl({offset:n,pieSettings:s,displayedData:t,cells:a})}),Nl=["key"],wl=["onMouseEnter","onClick","onMouseLeave"],kl=["id"],Sl=["id"];function qe(){return qe=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var n in a)({}).hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t},qe.apply(null,arguments)}function Rt(t,s){if(t==null)return{};var a,n,r=Cl(t,s);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(n=0;n<l.length;n++)a=l[n],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(r[a]=t[a])}return r}function Cl(t,s){if(t==null)return{};var a={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(s.indexOf(n)!==-1)continue;a[n]=t[n]}return a}function gs(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);s&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),a.push.apply(a,n)}return a}function ie(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?gs(Object(a),!0).forEach(function(n){Ml(t,n,a[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):gs(Object(a)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(a,n))})}return t}function Ml(t,s,a){return(s=$l(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function $l(t){var s=Fl(t,"string");return typeof s=="symbol"?s:s+""}function Fl(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var n=a.call(t,s);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}function Al(t){var s=b.useMemo(()=>oa(t.children,Ft),[t.children]),a=pt(n=>jl(n,t.id,s));return a==null?null:b.createElement(dr,{legendPayload:a})}function Pl(t){if(!(t==null||typeof t=="boolean"||typeof t=="function")){if(b.isValidElement(t)){var s,a=(s=t.props)===null||s===void 0?void 0:s.fill;
1return typeof a=="string"?a:void 0}var{fill:n}=t;return typeof n=="string"?n:void 0}}var Rl=b.memo(t=>{var{dataKey:s,nameKey:a,sectors:n,stroke:r,strokeWidth:l,fill:o,name:d,hide:c,tooltipType:m,id:p,activeShape:i}=t,h=Pl(i),v=n.map(L=>{var D=L.tooltipPayload;return h==null||D==null?D:D.map(j=>ie(ie({},j),{},{color:h,fill:h}))}),y={dataDefinedOnItem:v,getPosition:L=>{var D;return(D=n[Number(L)])===null||D===void 0?void 0:D.tooltipPosition},settings:{stroke:r,strokeWidth:l,fill:o,dataKey:s,nameKey:a,name:ra(d,s),hide:c,type:m,color:o,unit:"",graphicalItemId:p}};return b.createElement(xr,{tooltipEntrySettings:y})}),Dl=(t,s)=>t>s?"start":t<s?"end":"middle",Tl=(t,s,a)=>typeof s=="function"?ht(s(t),a,a*.8):ht(s,a,a*.8),Ll=(t,s,a)=>{var{top:n,left:r,width:l,height:o}=s,d=wr(l,o),c=r+ht(t.cx,l,l/2),m=n+ht(t.cy,o,o/2),p=ht(t.innerRadius,d,0),i=Tl(a,t.outerRadius,d),h=t.maxRadius||Math.sqrt(l*l+o*o)/2;return{cx:c,cy:m,innerRadius:p,outerRadius:i,maxRadius:h}},Ol=(t,s)=>{var a=St(s-t),n=Math.min(Math.abs(s-t),360);return a*n},El=(t,s)=>{if(b.isValidElement(t))return b.cloneElement(t,s);if(typeof t=="function")return t(s);var a=Yt("recharts-pie-label-line",typeof t!="boolean"?t.className:""),{key:n}=s,r=Rt(s,Nl);return b.createElement(kr,qe({},r,{type:"linear",className:a}))},Il=(t,s,a)=>{if(b.isValidElement(t))return b.cloneElement(t,s);var n=a;if(typeof t=="function"&&(n=t(s),b.isValidElement(n)))return n;var r=Yt("recharts-pie-label-text",Sr(t));return b.createElement(Cr,qe({},s,{alignmentBaseline:"middle",className:r}),n)};function zl(t){var{sectors:s,props:a,showLabels:n}=t,{label:r,labelLine:l,dataKey:o}=a;if(!n||!r||!s)return null;var d=la(a),c=ms(r),m=ms(l),p=typeof r=="object"&&"offsetRadius"in r&&typeof r.offsetRadius=="number"&&r.offsetRadius||20,i=s.map((h,v)=>{var y=(h.startAngle+h.endAngle)/2,L=Wt(h.cx,h.cy,h.outerRadius+p,y),D=ie(ie(ie(ie({},d),h),{},{stroke:"none"},c),{},{index:v,textAnchor:Dl(L.x,h.cx)},L),j=ie(ie(ie(ie({},d),h),{},{fill:"none",stroke:h.fill},m),{},{index:v,points:[Wt(h.cx,h.cy,h.outerRadius,y),L],key:"line"});return b.createElement(ca,{zIndex:ia.label,key:"label-".concat(h.startAngle,"-").concat(h.endAngle,"-").concat(h.midAngle,"-").concat(v)},b.createElement(rt,null,l&&El(l,j),Il(r,D,ze(h,o))))});return b.createElement(rt,{className:"recharts-pie-labels"},i)}function Bl(t){var{sectors:s,props:a,showLabels:n}=t,{label:r}=a;return typeof r=="object"&&r!=null&&"position"in r?b.createElement(Nr,{label:r}):b.createElement(zl,{sectors:s,props:a,showLabels:n})}function ql(t){var{sectors:s,activeShape:a,inactiveShape:n,allOtherPieProps:r,shape:l,id:o}=t,d=pt(fr),c=pt(gr),m=pt(yr),{onMouseEnter:p,onClick:i,onMouseLeave:h}=r,v=Rt(r,wl),y=Er(p,r.dataKey,o),L=Ir(h),D=zr(i,r.dataKey,o);return s==null||s.length===0?null:b.createElement(b.Fragment,null,s.map((j,M)=>{if(j?.startAngle===0&&j?.endAngle===0&&s.length!==1)return null;var f=m==null||m===o,w=String(M)===d&&(c==null||r.dataKey===c)&&f,B=d?n:null,z=a&&w?a:B,_=ie(ie({},j),{},{stroke:j.stroke,tabIndex:-1,[_r]:M,[br]:o});return b.createElement(rt,qe({key:"sector-".concat(j?.startAngle,"-").concat(j?.endAngle,"-").concat(j.midAngle,"-").concat(M),tabIndex:-1,className:"recharts-pie-sector"},jr(v,j,M),{onMouseEnter:y(j,M),onMouseLeave:L(j,M),onClick:D(j,M)}),b.createElement(vr,qe({option:l??z,index:M,shapeType:"sector",isActive:w},_)))}))}function Hl(t){var s,{pieSettings:a,displayedData:n,cells:r,offset:l}=t,{cornerRadius:o,startAngle:d,endAngle:c,dataKey:m,nameKey:p,tooltipType:i}=a,h=Math.abs(a.minAngle),v=Ol(d,c),y=Math.abs(v),L=n.length<=1?0:(s=a.paddingAngle)!==null&&s!==void 0?s:0,D=n.filter(z=>ze(z,m,0)!==0).length,j=(y>=360?D:D-1)*L,M=y-D*h-j,f=n.reduce((z,_)=>{var S=ze(_,m,0);return z+(xs(S)?S:0)},0),w;if(f>0){var B;w=n.map((z,_)=>{var S=ze(z,m,0),C=ze(z,p,_),u=Ll(a,l,z),g=(xs(S)?S:0)/f,A,x=ie(ie({},z),r&&r[_]&&r[_].props),P=x!=null&&"fill"in x&&typeof x.fill=="string"?x.fill:a.fill;_?A=B.endAngle+St(v)*L*(S!==0?1:0):A=d;var $=A+St(v)*((S!==0?h:0)+g*M),T=(A+$)/2,F=(u.innerRadius+u.outerRadius)/2,R=[{name:C,value:S,payload:x,dataKey:m,type:i,color:P,fill:P,graphicalItemId:a.id}],V=Wt(u.cx,u.cy,F,T);return B=ie(ie(ie(ie({},a.presentationProps),{}
1,{percent:g,cornerRadius:typeof o=="string"?parseFloat(o):o,name:C,tooltipPayload:R,midAngle:T,middleRadius:F,tooltipPosition:V},x),u),{},{value:S,dataKey:m,startAngle:A,endAngle:$,payload:x,paddingAngle:St(v)*L}),B})}return w}function Kl(t){var{showLabels:s,sectors:a,children:n}=t,r=b.useMemo(()=>!s||!a?[]:a.map(l=>({value:l.value,payload:l.payload,clockWise:!1,parentViewBox:void 0,viewBox:{cx:l.cx,cy:l.cy,innerRadius:l.innerRadius,outerRadius:l.outerRadius,startAngle:l.startAngle,endAngle:l.endAngle,clockWise:!1},fill:l.fill})),[a,s]);return b.createElement(hr,{value:s?r:void 0},n)}function Wl(t){var{props:s,previousSectorsRef:a,id:n}=t,{sectors:r,isAnimationActive:l,animationBegin:o,animationDuration:d,animationEasing:c,activeShape:m,inactiveShape:p,onAnimationStart:i,onAnimationEnd:h}=s,v=mr(s,"recharts-pie-"),y=a.current,[L,D]=b.useState(!1),j=b.useCallback(()=>{typeof h=="function"&&h(),D(!1)},[h]),M=b.useCallback(()=>{typeof i=="function"&&i(),D(!0)},[i]);return b.createElement(Kl,{showLabels:!L,sectors:r},b.createElement(ur,{animationId:v,begin:o,duration:d,isActive:l,easing:c,onAnimationStart:M,onAnimationEnd:j,key:v},f=>{var w,B=[],z=r&&r[0],_=(w=z?.startAngle)!==null&&w!==void 0?w:0;return r?.forEach((S,C)=>{var u=y&&y[C],g=C>0?pr(S,"paddingAngle",0):0;if(u){var A=ds(u.endAngle-u.startAngle,S.endAngle-S.startAngle,f),x=ie(ie({},S),{},{startAngle:_+g,endAngle:_+A+g});B.push(x),_=x.endAngle}else{var{endAngle:P,startAngle:$}=S,T=ds(0,P-$,f),F=ie(ie({},S),{},{startAngle:_+g,endAngle:_+T+g});B.push(F),_=F.endAngle}}),a.current=B,b.createElement(rt,null,b.createElement(ql,{sectors:B,activeShape:m,inactiveShape:p,allOtherPieProps:s,shape:s.shape,id:n}))}),b.createElement(Bl,{showLabels:!L,sectors:r,props:s}),s.children)}var Vl={animationBegin:400,animationDuration:1500,animationEasing:"ease",cx:"50%",cy:"50%",dataKey:"value",endAngle:360,fill:"#808080",hide:!1,innerRadius:0,isAnimationActive:"auto",label:!1,labelLine:!0,legendType:"rect",minAngle:0,nameKey:"name",outerRadius:"80%",paddingAngle:0,rootTabIndex:0,startAngle:0,stroke:"#fff",zIndex:ia.area};function Ql(t){var{id:s}=t,a=Rt(t,kl),{hide:n,className:r,rootTabIndex:l}=t,o=b.useMemo(()=>oa(t.children,Ft),[t.children]),d=pt(p=>vl(p,s,o)),c=b.useRef(null),m=Yt("recharts-pie",r);return n||d==null?(c.current=null,b.createElement(rt,{tabIndex:l,className:m})):b.createElement(ca,{zIndex:t.zIndex},b.createElement(Rl,{dataKey:t.dataKey,nameKey:t.nameKey,sectors:d,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,tooltipType:t.tooltipType,id:s,activeShape:t.activeShape}),b.createElement(rt,{tabIndex:l,className:m},b.createElement(Wl,{props:ie(ie({},a),{},{sectors:d}),previousSectorsRef:c,id:s})))}function Yl(t){var s=es(t,Vl),{id:a}=s,n=Rt(s,Sl),r=la(n);return b.createElement(or,{id:a,type:"pie"},l=>b.createElement(b.Fragment,null,b.createElement(cr,{type:"pie",id:l,data:n.data,dataKey:n.dataKey,hide:n.hide,angleAxisId:0,radiusAxisId:0,name:n.name,nameKey:n.nameKey,tooltipType:n.tooltipType,legendType:n.legendType,fill:n.fill,cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,paddingAngle:n.paddingAngle,minAngle:n.minAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius,cornerRadius:n.cornerRadius,presentationProps:r,maxRadius:s.maxRadius}),b.createElement(Al,qe({},n,{id:l})),b.createElement(Ql,qe({},n,{id:l}))))}var ya=Yl;ya.displayName="Pie";function Gl(t){var s=Mr();return b.useEffect(()=>{s($r(t))},[s,t]),null}var Ul=["layout"];function Vt(){return Vt=Object.assign?Object.assign.bind():function(t){for(var s=1;s<arguments.length;s++){var a=arguments[s];for(var n in a)({}).hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t},Vt.apply(null,arguments)}function Jl(t,s){if(t==null)return{};var a,n,r=Xl(t,s);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(t);for(n=0;n<l.length;n++)a=l[n],s.indexOf(a)===-1&&{}.propertyIsEnumerable.call(t,a)&&(r[a]=t[a])}return r}function Xl(t,s){if(t==null)return{};var a={};for(var n in t)if({}.hasOwnProperty.call(t,n)){if(s.indexOf(n)!==-1)continue;a[n]=t[n]}return a}function ys(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);
1s&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),a.push.apply(a,n)}return a}function Zl(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?ys(Object(a),!0).forEach(function(n){ei(t,n,a[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):ys(Object(a)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(a,n))})}return t}function ei(t,s,a){return(s=ti(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function ti(t){var s=si(t,"string");return typeof s=="symbol"?s:s+""}function si(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var n=a.call(t,s);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}var ai={top:5,right:5,bottom:5,left:5},ba=Zl({accessibilityLayer:!0,stackOffset:"none",barCategoryGap:"10%",barGap:4,margin:ai,reverseStackOrder:!1,syncMethod:"index",layout:"radial",responsive:!1,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"},Lr),ni=b.forwardRef(function(s,a){var n,r=es(s.categoricalChartProps,ba),{layout:l}=r,o=Jl(r,Ul),{chartName:d,defaultTooltipEventType:c,validateTooltipEventTypes:m,tooltipPayloadSearcher:p}=s,i={chartName:d,defaultTooltipEventType:c,validateTooltipEventTypes:m,tooltipPayloadSearcher:p,eventEmitter:void 0};return b.createElement(Fr,{preloadedState:{options:i},reduxStoreName:(n=r.id)!==null&&n!==void 0?n:d},b.createElement(Ar,{chartData:r.data}),b.createElement(Pr,{layout:l,margin:r.margin}),b.createElement(Rr,{throttleDelay:r.throttleDelay,throttledEvents:r.throttledEvents}),b.createElement(Dr,{baseValue:void 0,accessibilityLayer:r.accessibilityLayer,barCategoryGap:r.barCategoryGap,maxBarSize:r.maxBarSize,stackOffset:r.stackOffset,barGap:r.barGap,barSize:r.barSize,syncId:r.syncId,syncMethod:r.syncMethod,className:r.className,reverseStackOrder:r.reverseStackOrder}),b.createElement(Gl,{cx:r.cx,cy:r.cy,startAngle:r.startAngle,endAngle:r.endAngle,innerRadius:r.innerRadius,outerRadius:r.outerRadius}),b.createElement(Tr,Vt({},o,{ref:a})))});function bs(t,s){var a=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);s&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(t,r).enumerable})),a.push.apply(a,n)}return a}function _s(t){for(var s=1;s<arguments.length;s++){var a=arguments[s]!=null?arguments[s]:{};s%2?bs(Object(a),!0).forEach(function(n){ri(t,n,a[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(a)):bs(Object(a)).forEach(function(n){Object.defineProperty(t,n,Object.getOwnPropertyDescriptor(a,n))})}return t}function ri(t,s,a){return(s=li(s))in t?Object.defineProperty(t,s,{value:a,enumerable:!0,configurable:!0,writable:!0}):t[s]=a,t}function li(t){var s=ii(t,"string");return typeof s=="symbol"?s:s+""}function ii(t,s){if(typeof t!="object"||!t)return t;var a=t[Symbol.toPrimitive];if(a!==void 0){var n=a.call(t,s);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(s==="string"?String:Number)(t)}var oi=["item"],ci=_s(_s({},ba),{},{layout:"centric",startAngle:0,endAngle:360}),di=b.forwardRef((t,s)=>{var a=es(t,ci);return b.createElement(ni,{chartName:"PieChart",defaultTooltipEventType:"item",validateTooltipEventTypes:oi,tooltipPayloadSearcher:Or,categoricalChartProps:a,ref:s})});const nt={leadership:"Leadership",rn:"RN",lpn:"LPN",cna:"CNA",social_work:"Social Work",admin:"Admin",don:"DON"},xi={1:"Administrator",5:"DON",6:"RN (admin)",7:"RN",8:"LPN (admin)",9:"LPN",10:"CNA",11:"Aide in training",12:"Med aide",14:"CNS",30:"Social Worker",31:"SW (other)"},Mt=1e3*60*60*24,Re={leadership:"#475569",rn:"#0284c7",lpn:"#94a3b8",cna:"#64748b",social_work:"#cbd5e1",admin:"#475569",don:"#334155"};function ke(t){if(t==null)return"--";if(t>=1825)return"5+ yr";if(t<90)return`${t}d`;if(t<365)return`${Math.round(t/30)}mo`;const s=Math.floor(t/365),a=Math.round(t%365/30);return a>0?`${s}y ${a}mo`:`${s}y`}function Be(t){return t&&`Q${t.slice(5)} '${t.slice(2,4)}`}function mi(t){const[s,a]=t.split("_").map(Number);
1return new Date(s,(a-1)*3,1)}function ui(t){const[s,a]=t.split("_").map(Number);return new Date(s,a*3,0)}function pi(t,s){if(!t||!s)return[];const a=[];let[n,r]=t.split("_").map(Number);const[l,o]=s.split("_").map(Number);for(;n<l||n===l&&r<=o;)a.push(`${n}_${r}`),r++,r>4&&(r=1,n++);return a}function hi(t,s){if(!t)return null;const[a,n]=t.split("_"),r=`${Number(a)-1}_${n}`;return s.includes(r)?r:null}function fi({ccn:t,facility:s}){const{user:a}=qs(),[n,r]=b.useState("detail"),l=!!a?.is_admin,o=[{key:"detail",label:"Staffing Detail"},...l?[{key:"scorecard",label:"Staffing Star Scorecard"}]:[]];return e.jsxs("div",{className:"space-y-4",children:[o.length>1&&e.jsx("div",{className:"flex gap-1 border-b border-slate-200",children:o.map(d=>e.jsx("button",{onClick:()=>r(d.key),className:`px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors ${n===d.key?"border-sky-600 text-sky-700":"border-transparent text-slate-500 hover:text-slate-700"}`,children:d.label},d.key))}),l&&n==="scorecard"&&e.jsx(gi,{ccn:t,facility:s}),n==="detail"&&e.jsx(yi,{ccn:t,facility:s})]})}function gi({ccn:t,facility:s}){const{data:a,isLoading:n}=ee({queryKey:["staffing-scorecard",t],queryFn:()=>za(t),enabled:!!t}),[r,l]=b.useState(()=>new Set),o=_=>l(S=>{const C=new Set(S);return C.has(_)?C.delete(_):C.add(_),C}),[d,c]=b.useState(!1);if(n)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ge,{className:"animate-spin text-sky-500",size:32})});if(!a)return e.jsx("div",{className:"text-center py-16 text-slate-400",children:"No staffing rating data available."});const m=a.cms_staffing_rating,p=a.estimated_star,i=_=>{try{return new Date(_).toLocaleDateString("en-US",{month:"short",year:"numeric"})}catch{return"the prior period"}},h=(_,S)=>{const C=S>0?_/S:0;return C>=.8?"#075985":C>=.6?"#0284c7":C>=.4?"#38bdf8":"#bae6fd"},v={5:"bg-emerald-100 text-emerald-800",4:"bg-sky-100 text-sky-800",3:"bg-amber-100 text-amber-800",2:"bg-orange-100 text-orange-800",1:"bg-red-100 text-red-800"},y=({star:_,label:S,onClick:C})=>e.jsxs("div",{className:`text-center ${C?"cursor-pointer group":""}`,onClick:C,children:[e.jsx("span",{className:`inline-block px-3 py-1 rounded-full text-lg font-bold ${v[_]||"bg-slate-100 text-slate-800"} ${C?"group-hover:ring-2 ring-sky-300 transition-all":""}`,children:_?`${_} â
`:"â"}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:S}),C&&e.jsx("p",{className:"text-[9px] text-sky-500 opacity-0 group-hover:opacity-100 transition-opacity",children:"cut points â"})]}),L=({points:_,max:S,color:C,segments:u=10})=>{const g=S/u,A=_!=null?Math.round(_/g):0;return e.jsx("span",{className:"flex gap-[2px] h-5 w-full items-stretch",title:`${_??0} of ${S} points â ${A} of ${u} steps`,children:Array.from({length:u}).map((x,P)=>e.jsx("span",{className:"flex-1 rounded-[2px]",style:{backgroundColor:P<A?C:"#e8edf3"}},P))})},D=_=>{const S=_.next_tier;return!S||S.band_lo==null?null:_.unit==="hprd"?`next: ${S.band_hi==null?`${S.band_lo}+ hrs`:`${S.band_lo}â${S.band_hi} hrs`} â +${S.gain}`:_.unit==="pct"?`next: ${S.band_lo}â${S.band_hi}% â +${S.gain}`:null},j=()=>{const _=a.star_thresholds||[155,205,255,320],S=380,C=[[0,_[0],1],[_[0],_[1],2],[_[1],_[2],3],[_[2],_[3],4],[_[3],S,5]],u=a.total??0,g=_.find(A=>u<A);return e.jsxs("div",{className:"mt-3 px-4 py-3 rounded-lg bg-slate-50 border border-slate-200",children:[e.jsxs("p",{className:"text-xs font-semibold text-slate-700 mb-2",children:["Staffing point bands (your total: ",u," of ",S,")"]}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"flex w-full h-6 rounded overflow-hidden gap-px",children:C.map(([A,x,P])=>{const $={1:"#e0f2fe",2:"#bae6fd",3:"#7dd3fc",4:"#38bdf8",5:"#0284c7"},T=(a.total??0)>=A&&(a.total??0)<x;return e.jsxs("div",{className:`flex items-center justify-center text-[9px] font-semibold ${P>=4?"text-white":"text-slate-600"} ${T?"ring-2 ring-slate-700 ring-inset":""}`,style:{width:`${(x-A)/S*100}%`,backgroundColor:$[P]},title:`${P}â
: ${A}â${x===S?S:x-1} pts`,children:[P,"â
"]},P)})}),e.jsx("div",{className:"absolute -top-1 -bottom-1 flex flex-col items-center",style:{left:`calc(${Math.min(100,u/S*100)}% - 1px)`},children:e.jsx("span",{className:"w-0.5 h-8 bg-slate-800"})})]}),e.jsx("div",{className:"flex justify-between text-[9px] text-slate-400 mt-1",children:C.map(([A,x,P])=>e.jsxs("span",{children:[A,P===5?`â${S}`:""]},P))}),e.jsxs("p",{className:"text-[11px] text-slate-500 mt-2",children:["You're at ",e.jsx("strong",{children:u})," (",a.cms_staffing_rating,"â
from CMS)."," ",g?`${g-u} more points reaches ${_.indexOf(g)+2}â
.`:"Top band."]})]})},M=({m:_,open:S,onToggle:C})=>{const u=_.points!=null?h(_.points,_.max_points):"#e2e8f0",g=_.unit==="hprd",A=_.delta_dir==="better"?"text-emerald-600":_.delta_dir==="worse"?"text-rose-600":"text-slate-500",x=g&&_.reported!=null||_.decile!=null||_.delta_display&&_.delta_display!=="no change";return e.jsxs("div",{className:"border-b border-slate-50 last:border-0",children:[e.jsxs("button",{onClick:x?C:void 0,className:`w-full flex items-center gap-3 py-2.5 text-left ${x?"cursor-pointer hover:bg-slate-50/70 rounded":"cursor-default"}`,children:[e.jsx("span",{className:"w-4 shrink-0 text-slate-400",children:x&&(S?e.jsx(ye,{size:14}):e.jsx(gt,{size:14}))}),e.jsx("span",{className:"w-36 sm:w-44 min-w-0 text-[13px] font-medium text-slate-700 truncate",title:_.info||void 0,children:_.label}),e.jsx("span",{className:"w-16 text-right text-sm font-semibold text-slate-700",children:_.display_value}),e.jsxs("span",{className:"flex-1 min-w-[90px] flex flex-col gap-1",children:[e.jsx(L,{points:_.points,max:_.max_points,color:u}),D(_)&&e.jsx("span",{className:"text-[9px] text-slate-400 leading-none",children:D(_)})]}),e.jsxs("span",{className:"w-14 text-right",children:[e.jsx("span",{className:"text-base font-bold text-slate-700",children:_.points??"â"}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:["/",_.max_points]})]})]}),S&&x&&e.jsxs("div",{className:"pl-7 pb-2.5 text-[11px] text-slate-500 space-y-0.5",children:[g&&_.reported!=null&&_.value!=null&&e.jsxs("div",{children:["reported ",_.reported.toFixed(2)," â adjusted ",_.value.toFixed(2)," hrs/day",_.acuity_dir&&_.acuity_dir!=="average"&&` · residents ~${_.acuity_pct}% ${_.acuity_dir} acuity than national`]}),g&&_.acuity_multiplier!=null&&e.jsxs("div",{className:"text-slate-600",children:["At your acuity, ",e.jsxs("strong",{children:["each extra reported hour/resident-day counts as ~",_.acuity_multiplier,"à adjusted"]})," toward the rating."]}),_.decile!=null&&e.jsxs("div",{children:["national decile ",_.decile," of 10 · earns ",_.points,"/",_.max_points," points"]}),_.delta_display&&_.delta_display!=="no change"&&e.jsxs("div",{className:A,children:[_.delta_display," vs prior period",_.delta_dir==="worse"?" â worsened":_.delta_dir==="better"?" â improved":""]})]})]})},f=a.state_rank&&a.state_total?Math.round((1-(a.state_rank-1)/a.state_total)*100):null,w=f==null?"":f>=75?"text-emerald-600":f>=50?"text-sky-600":f>=25?"text-amber-600":"text-red-600",B=(a.measures||[]).filter(_=>_.next_tier&&_.decile!=null&&_.decile<10).sort((_,S)=>S.max_points-_.max_points||_.decile-S.decile).slice(0,5),z=_=>{const S=_.next_tier;if(_.unit==="hprd"){if(S.add_hours_day!=null){let C=`Add ~${S.add_hours_day} nurse-hours/day (about ${S.add_ftes} full-time staff) at ~${Math.round(a.census)} residents.`;return _.acuity_multiplier!=null?C+=` At your acuity each hour counts as ~${_.acuity_multiplier}à adjusted, lifting the rated figure to ${S.target} hrs â the next decile, +${S.gain} points.`:C+=` That lifts the adjusted figure to ${S.target} hrs for +${S.gain} points.`,C}return`Reach ${S.target} adjusted hrs (about +${S.gap_min} min/resident-day) for +${S.gain} points.`}return _.unit==="pct"?`Bring this down about ${S.gap_pp} points (to ${S.target}% or lower) for +${S.gain} points â retention, not new hires, is the lever.`:""};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-bold text-slate-800",children:"CMS Five-Star Staffing Scorecard"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 max-w-xl",children:"The six staffing measures CMS uses, each scored against national levels. The star at right is CMS's official staffing rating; the points below show what drives it."})]}),e.jsxs("div",{className:"flex items-center gap-3 md:gap-6",children:[e.jsxs("div",{children:[e.jsx(y,{star:m,label:"CMS Staffing",onClick:()=>c(_=>!_)}),a.state_rank&&e.jsxs("p",{className:`text-[11px] font-medium mt
1-0.5 text-center ${w}`,children:["#",a.state_rank," of ",a.state_total," in ",a.state]})]}),p!=null&&p!==m&&e.jsx("div",{className:"border-l border-slate-200 pl-3 md:pl-6",children:e.jsx(y,{star:p,label:"Estimated"})})]})]}),d&&e.jsx(j,{})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-2",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800",children:["Staffing Measures (",a.measures_available," of 6)"]}),e.jsxs("p",{className:"text-[11px] text-slate-500 mt-0.5 max-w-lg",children:["CMS scores six measures on a 380-point scale by national decile. Click any row for the reportedâadjusted hours, acuity, and ",a.prior_period?`change since ${i(a.prior_period)}`:"change vs the prior period","."]})]}),e.jsxs("div",{className:"text-right shrink-0 pl-3",children:[e.jsx("span",{className:"text-lg font-bold text-slate-800",children:a.total}),e.jsxs("span",{className:"text-sm text-slate-400",children:["/",a.max_total]}),e.jsx("p",{className:"text-[10px] text-slate-400",children:"staffing points"}),a.census!=null&&e.jsxs("p",{className:"text-[10px] text-slate-400",children:["~",Math.round(a.census)," residents/day"]})]})]}),e.jsx("div",{className:"mt-2",children:a.measures.map(_=>e.jsx(M,{m:_,open:r.has(_.code),onToggle:()=>o(_.code)},_.code))}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-2 pt-2 border-t border-slate-100",children:"Star bands: 1â
<155 · 2â
155â204 · 3â
205â254 · 4â
255â319 · 5â
320â380. Hours are case-mix adjusted for resident acuity."})]}),B.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsx("h3",{className:"text-sm font-bold text-slate-800",children:"Where to gain points"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 mb-3",children:"Points are awarded by national decile. The RN and total-nurse-hour measures are worth the most (100 points each), so adding nurse time usually moves the score fastest. Below, what it would take to climb to the next decile on each measure that isn't already at the top â in real terms for this home."}),e.jsx("div",{className:"space-y-2",children:B.map((_,S)=>e.jsxs("div",{className:"flex items-start gap-3 py-2 px-3 rounded-lg bg-slate-50",children:[e.jsxs("span",{className:"text-xs font-semibold text-slate-500 w-4 pt-0.5",children:[S+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-700",children:[_.label," ",e.jsxs("span",{className:"text-slate-400 font-normal",children:["â now ",_.display_value," (",_.points,"/",_.max_points," pts, decile ",_.decile,")"]})]}),e.jsx("p",{className:"text-[11px] text-slate-600 mt-0.5",children:z(_)})]})]},_.code))})]}),e.jsx("p",{className:"text-[11px] text-slate-400 italic leading-relaxed",children:"Built on the CMS Five-Star Technical Users' Guide (Table A2 fixed cut points) and Payroll-Based Journal (PBJ) data, published in CMS's monthly Provider Information file. Hours are case-mix adjusted for resident acuity. The headline star is CMS's own; the points reproduce CMS's published method and match its rating for ~93% of homes. CMS can also force a 1-star rating for data problems (e.g. zero RN hours on several days or a missed PBJ deadline) that the points alone don't capture."})]})}function yi({ccn:t,facility:s}){const a=ee({queryKey:["staffing-summary",t],queryFn:()=>Ba(t),enabled:!!t}),n=ee({queryKey:["staffing-agency",t],queryFn:()=>qa(t),enabled:!!t}),r=ee({queryKey:["staffing-turnover",t],queryFn:()=>Qs(t,{role:"leadership"}),enabled:!!t}),l=ee({queryKey:["staffing-tenure",t],queryFn:()=>qt(t),enabled:!!t}),o=ee({queryKey:["staffing-turnover-rate",t],queryFn:()=>Ha(t),enabled:!!t}),d=a.isLoading,c=a.isError&&a.error?.message?.includes("404");return d?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ge,{className:"animate-spin text-sky-500",size:32})}):c?e.jsxs("div",{className:"text-center py-16 text-slate-400",children:[e.jsx(Hs,{size:48,className:"mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-lg font-medium",children:"No PBJ staffing data available for this facility."}),e.jsx("p",{className:"text-sm mt-1",children:"PBJ data covers Q2 2020 - Q3 2025."})]}):e.jsxs("div",{className:"space-y-6",children:[s&&e.jsx(vi,{facility:s,ccn:t}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-2 gap-6 items-stretch",children:[a.data&&e.jsx(ji,{data:a.data,ccn:t}),o.data&&e.jsx(_i,{data:o.data})]}),r.data&&e.jsx(Ci,{data:r.data,ccn:t}),n.data&&e.jsx(Ni,{data:n.data}),l.data&&e.jsx(wi,{data:l.data,ccn:t})]})}function dt({label:t,value:s,tip:a,action:n,sub:r,stateAvg:l,localAvg:o,groupStart:d,valueTone:c="text-slate-900"}){return e.jsxs("tr",{className:d?"border-t border-slate-200":"border-t border-slate-100",children:[e.jsx("td",{className:"py-2.5 pr-2 text-slate-600",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:t}),a&&e.jsx(le,{text:a}),n]})}),e.jsxs("td",{className:"py-2.5 text-right",children:[e.jsx("span",{className:`font-semibold ${c}`,children:s}),r&&e.jsx("span",{className:"block text-[10px] text-slate-400 leading-tight",children:r})]}),e.jsx("td",{className:"py-2.5 text-right text-slate-500",children:l??"â"}),e.jsx("td",{className:"py-2.5 text-right text-slate-500",children:o??"â"})]})}const bi=t=>{const[s,a]=String(t).split("-");return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][parseInt(a,10)-1]} ${s}`};function _i({data:t}){const s=t;if(!s||!s.roles?.length&&!s.excluded_reason)return null;const a=m=>m==null?"â":`${m.toFixed(1)}%`;
1(s.roles||[]).find(m=>m.role==="total");const n=s.full_time||[],[r,l]=b.useState(!1),o=(s.trend||[]).filter(m=>m.total!=null),d=o[0],c=o[o.length-1];return e.jsxs("section",{className:"space-y-4 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h2",{className:"section-heading flex items-center gap-2",children:[e.jsx(Ws,{size:14,className:"text-slate-400"}),"Turnover"]}),e.jsx("span",{className:"text-xs text-slate-400",children:s.measure_end?`12 months ending ${bi(s.measure_end)}`:"Annual turnover"}),s.measure_end&&e.jsx(le,{text:"The most recent period available. This counts departures during the 12 months shown; payroll data through March 2026 is used to confirm them, because a departure is defined as ninety consecutive days with no worked shift and that gap has to be observed after the fact. Someone who left in 2026 is not counted here. The measure needs six consecutive quarters in total, so the latest complete period trails the present by about two quarters. CMS's currently published turnover covers this same period."})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm px-5 py-1 flex-1",children:[s.excluded_reason?e.jsxs("div",{className:"py-6 text-sm text-slate-500",children:[e.jsx("p",{className:"font-medium text-slate-600 mb-1",children:"Turnover is not reportable for this facility."}),e.jsx("p",{className:"text-xs leading-relaxed",children:s.excluded_reason==="id_renumbering"?"Employee identifiers in this facilityâs payroll submissions were reissued during the period, which makes existing staff appear to leave at once. CMS allows facilities to submit a crosswalk merging those records. This is a reporting artifact, not a measure of retention.":s.excluded_reason==="incomplete_quarters"?"One or more of the six payroll quarters required for the annual turnover measure is missing.":"Fewer than five eligible nursing staff, which is below the threshold at which the rate is stable."})]}):e.jsxs("table",{className:"w-full text-sm tabular-nums",children:[e.jsxs("colgroup",{children:[e.jsx("col",{}),e.jsx("col",{className:"w-28"}),e.jsx("col",{className:"w-20"}),e.jsx("col",{className:"w-24"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-slate-400",children:[e.jsx("th",{scope:"col",className:"text-left font-medium py-2",children:"Role"}),e.jsx("th",{scope:"col",className:"text-right font-medium py-2",children:"This Facility"}),e.jsx("th",{scope:"col",className:"text-right font-medium py-2",children:"State Avg"}),e.jsx("th",{scope:"col",className:"text-right font-medium py-2 whitespace-nowrap",children:"Local Avg"})]})}),e.jsxs("tbody",{children:[s.roles.map((m,p)=>e.jsxs("tr",{className:p===0?"border-t border-slate-200":"border-t border-slate-100",children:[e.jsx("td",{className:"py-2.5 pr-2 text-slate-600",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:m.role==="total"?"font-medium text-slate-700":"",children:m.label}),m.role==="total"&&e.jsx(le,{text:"Percentage of nursing staff who left over the year, reproducing the CMS staff turnover measure from payroll records. A departure is ninety consecutive days with no worked shift, so extended leave counts as turnover."}),m.role==="lpn"&&e.jsx(le,{text:"LPN and nurse aide turnover are not published by CMS. They are calculated here using the same method as the combined figure."})]})}),e.jsxs("td",{className:"py-2.5 text-right",children:[e.jsx("span",{className:"font-semibold text-slate-900",children:a(m.turnover)}),m.spells!=null&&e.jsx("span",{className:"block text-[10px] text-slate-400 leading-tight",children:m.departures!=null?`${m.departures} of ${m.spells} left`:`${m.spells} tracked`})]}),e.jsx("td",{className:"py-2.5 text-right text-slate-500",children:a(m.state_avg)}),e.jsxs("td",{className:"py-2.5 text-right",children:[e.jsx("span",{className:"text-slate-500",children:a(m.local_avg)}),m.local_rank&&e.jsxs("span",{className:"block text-[10px] text-slate-400 leading-tight",children:["#",m.local_rank," of ",m.local_total]})]})]},m.role)),n.length>0&&e.jsx("tr",{className:"border-t-2 border-slate-200",children:e.jsx("td",{colSpan:4,className:"py-2",children:e.jsxs("button",{onClick:()=>l(m=>!m),"aria-expanded":r,className:"flex items-center gap-1.5 text-[10px] uppercase tracking-wide text-slate-400 font-medium hover:text-slate-600 transition-colors",children:[r?e.jsx(ye,{size:12}):e.jsx(gt,{size:12}),"Full-time share by role"]})})}),r&&n.map(m=>e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"py-2.5 pr-2 text-slate-600",children:e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{children:m.label}),m.role==="cna"&&e.jsx(le,{text:"Share of directly employed nursing staff working full-time, defined as 30 or more hours per week averaged over the weeks they were attached to the facility. Agency staff are excluded because they are casual by nature. PBJ excludes meal breaks and all paid leave, so 30 hours allows for ordinary time off. HIGHER is better here, unlike the turnover rows above. Not published by CMS."})]})}),e.jsxs("td",{className:"py-2.5 text-right",children:[e.jsx("span",{className:"font-semibold text-slate-900",children:a(m.ft_pct)}),m.employees!=null&&e.jsxs("span",{className:"block text-[10px] text-slate-400 leading-tight",children:[m.ft_count," of ",m.employees]})]}),e.jsx("td",{className:"py-2.5 text-right text-slate-500",children:a(m.state_avg)}),e.jsx("td",{className:"py-2.5 text-right",children:m.vs_state==null?e.jsx("span",{className:"text-slate-300",children:"â"}):Math.abs(m.vs_state)<.5?e.jsx("span",{className:"text-slate-400",children:"in line"}):e.jsxs("span",{className:m.vs_state>0?"text-slate-700 font-medium":"text-slate-500",children:[m.vs_state>
10?"above":"below",e.jsxs("span",{className:"text-[10px] text-slate-400 ml-1",children:["by ",Math.abs(m.vs_state).toFixed(1)]})]})})]},`ft-${m.role}`))]})]}),!s.excluded_reason&&o.length>=2&&e.jsxs("p",{className:"text-xs text-slate-500 border-t border-slate-100 py-2.5",children:["All-nursing turnover ",c.total<d.total?"down":"up"," ",e.jsxs("span",{className:"font-medium text-slate-700",children:[Math.abs(c.total-d.total).toFixed(1)," points"]})," ","since ",d.measure_year," (",d.total.toFixed(1),"% to ",c.total.toFixed(1),"%)."]})]})]})}function ji({data:t,ccn:s}){const a=t,[n,r]=b.useState(!1),l=ee({queryKey:["staffing-new-hires-trend",s],queryFn:()=>Ka(s),enabled:n}),o=m=>m&&m.total?`Top ${Math.max(1,Math.round(m.rank/m.total*100))}%`:null,d=m=>m!=null?ke(m):null,c=a.local_avgs?.total||null;return e.jsxs("section",{className:"space-y-4 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h2",{className:"section-heading flex items-center gap-2",children:[e.jsx(Ks,{size:14,className:"text-slate-400"}),"Staffing Stability Overview"]}),e.jsx("span",{className:"text-xs text-slate-400",children:a.latest_quarter})]}),e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm px-5 py-1 flex-1",children:e.jsxs("table",{className:"w-full text-sm tabular-nums",children:[e.jsxs("colgroup",{children:[e.jsx("col",{}),e.jsx("col",{className:"w-32"}),e.jsx("col",{className:"w-24"}),e.jsx("col",{className:"w-24"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-slate-400",children:[e.jsx("th",{scope:"col",className:"text-left font-medium py-2",children:"Metric"}),e.jsx("th",{scope:"col",className:"text-right font-medium py-2",children:"This Facility"}),e.jsx("th",{scope:"col",className:"text-right font-medium py-2",children:"State Avg"}),e.jsxs("th",{scope:"col",className:"text-right font-medium py-2",children:["Local Avg",c?e.jsxs("span",{className:"normal-case tracking-normal text-slate-300",children:[" · ",c," near"]}):""]})]})}),e.jsxs("tbody",{children:[e.jsx(dt,{label:"Admin Tenure",value:ke(a.admin_tenure_days),sub:o(a.state_ranks?.admin),stateAvg:d(a.state_avgs?.admin),localAvg:d(a.local_avgs?.admin),tip:"Tenure of most recent administrator. Multiple transitions indicate instability."}),e.jsx(dt,{label:"DON Tenure",value:ke(a.don_tenure_days),sub:o(a.state_ranks?.don),stateAvg:d(a.state_avgs?.don),localAvg:d(a.local_avgs?.don),tip:"Tenure of most recent Director of Nursing. DON turnover correlates with quality issues."}),e.jsx(dt,{label:"Nursing Admin",value:ke(a.nursing_admin_tenure_days),sub:o(a.state_ranks?.nursing_admin),stateAvg:d(a.state_avgs?.nursing_admin),localAvg:d(a.local_avgs?.nursing_admin),tip:"Median tenure of active RN and LPN staff with administrative duties (charge nurses, shift supervisors) as of end of quarter."}),e.jsx(dt,{label:"Social Services",value:ke(a.social_services_tenure_days),sub:o(a.state_ranks?.social_services),stateAvg:d(a.state_avgs?.social_services),localAvg:d(a.local_avgs?.social_services),tip:"Median tenure of active social services staff (social workers) as of end of quarter. Handles discharge planning, family communication, and care transitions."}),e.jsx(dt,{groupStart:!0,label:"New Hires R12",value:a.new_hires_12mo!=null?a.new_hires_12mo:"--",sub:"RN + LPN + CNA",tip:"Distinct nursing employees whose first appearance in PBJ data falls within the trailing 12 months.",action:e.jsx("button",{onClick:()=>r(!n),className:`p-0.5 rounded ${n?"text-sky-600":"text-slate-400 hover:text-slate-600"}`,title:"Show quarterly trend","aria-label":"Show new hires quarterly trend",children:e.jsx(Ea,{size:14})})})]})]})}),n&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-800",children:"New Nursing Hires by Quarter"}),e.jsx("button",{onClick:()=>r(!1),className:"text-xs text-slate-400 hover:text-slate-600",children:"Close"})]}),l.isLoading?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ge,{className:"animate-spin text-sky-400",size:20})}):l.data?.trend?.length?e.jsx(je,{width:"100%",height:220,children:e.jsxs(it,{data:l.data.trend.map(m=>({...m,quarter:Be(m.quarter)})),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"quarter",tick:{fontSize:10,fill:"#64748b"}}),e.jsx(xe,{tick:{fontSize:11,fill:"#64748b"},allowDecimals:!1}),e.jsx(ce,{contentStyle:{fontSize:12,borderRadius:8,border:"1px solid #e2e8f0"},formatter:(m,p)=>
1[m,{rn:"RN",lpn:"LPN",cna:"CNA"}[p]||p]}),e.jsx(Fe,{wrapperStyle:{fontSize:11}}),e.jsx(_e,{dataKey:"rn",stackId:"1",fill:Re.rn,name:"rn"}),e.jsx(_e,{dataKey:"lpn",stackId:"1",fill:Re.lpn,name:"lpn"}),e.jsx(_e,{dataKey:"cna",stackId:"1",fill:Re.cna,name:"cna"})]})}):e.jsx("p",{className:"text-sm text-slate-400 text-center py-6",children:"No new hire data available."})]})]})}function vi({facility:t,ccn:s}){const{data:a}=ee({queryKey:["facility-staffing-context",s],queryFn:()=>Wa(s),enabled:!!s,staleTime:3e5}),n=a?.state_medians||{},r=a?.competitor_ranks||{},l=a?.state?`${a.state} Median`:"State Median",o=[{label:"RN",key:"rn",reported:t.reported_rn_hprd,benchmark:t.casemix_rn_hprd},{label:"LPN",key:"lpn",reported:t.reported_lpn_hprd,benchmark:t.casemix_lpn_hprd},{label:"CNA / Aide",key:"aide",reported:t.reported_aide_hprd,benchmark:t.casemix_aide_hprd},{label:"Total Nursing",key:"total_nurse",reported:t.reported_total_nurse_hprd,benchmark:t.casemix_total_nurse_hprd,bold:!0}].map(y=>{const L=y.reported!=null?Number(y.reported):null,D=y.benchmark!=null?Number(y.benchmark):null,j=n[y.key]!=null?Number(n[y.key]):null,M=L!=null&&D!=null?+(L-D).toFixed(3):null,f=L!=null&&j!=null?+(L-j).toFixed(3):null,w=r[y.key]||null;return{...y,rep:L,bm:D,sm:j,diffBm:M,diffSm:f,rank:w}});if(!o.some(y=>y.rep!=null))return null;const m=[...o.filter(y=>y.diffSm!=null)].sort((y,L)=>(y.diffSm??0)-(L.diffSm??0))[0],p=m?m.diffSm>=0?`Staffed at or above ${l.toLowerCase()} across all nursing roles.`:`Staffed ${Math.abs(m.diffSm).toFixed(2)} hrs/day below ${l.toLowerCase()} on ${m.label}.`:null;function i(y){return y==null?"text-slate-300":y<=-.3?"text-slate-500":y>=.3?"text-slate-800":"text-slate-400"}function h(y){return y==null?"â":`${y>=0?"+":""}${y.toFixed(2)}`}function v(y,L){if(!y||!L)return"text-slate-300";const D=y/L;return D<=.25?"text-slate-800":D>=.75?"text-slate-500":"text-slate-600"}return e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"section-heading flex items-center gap-2",children:[e.jsx(Ks,{size:14,className:"text-slate-400"}),"Staffing Adequacy",e.jsx(le,{text:"Compares reported nursing hours per resident per day (HPRD) against three references: (1) CMS Case-Mix Adjusted â national peer estimate based on resident acuity from MDS assessments; (2) State Median â middle reported value across all SNFs in the state, reflecting local staffing norms and mandates; (3) Local Rank â position among the 10 nearest competitors by distance."})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("table",{className:"w-full text-sm table-fixed tabular-nums",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[18%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[14%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[13%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[13%]"})]}),e.jsx("thead",{className:"border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left font-medium text-slate-500 text-[10px] uppercase tracking-wide py-2",children:"Role"}),e.jsx("th",{scope:"col",className:"text-right font-medium text-slate-500 text-[10px] uppercase tracking-wide py-2",children:"Reported"}),e.jsx("th",{scope:"col",className:"text-right font-medium text-slate-500 text-[10px] uppercase tracking-wide py-2",children:"CMS Case Mix Adj"}),e.jsx("th",{scope:"col",className:"text-right font-medium text-slate-400 text-[10px] uppercase tracking-wide py-2",children:"vs CM"}),e.jsx("th",{scope:"col",className:"text-right font-medium text-slate-500 text-[10px] uppercase tracking-wide py-2",children:l}),e.jsx("th",{scope:"col",className:"text-right font-medium text-slate-400 text-[10px] uppercase tracking-wide py-2",children:"vs State"}),e.jsx("th",{scope:"col",className:"text-right font-medium text-slate-500 text-[10px] uppercase tracking-wide py-2",children:"Local Rank"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:o.map((y,L)=>e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:`py-2.5 ${y.bold?"font-semibold text-slate-800":"text-slate-600"}`,children:y.label}),e.jsx("td",{className:`py-2.5 text-right ${y.bold?"font-semibold text-slate-800":"text-slate-700"}`,children:y.rep!=null?y.rep.toFixed(2):"â"}),e.jsx("td",{className:"py-2.5 text-right text-slate-500",children:y.bm!=null?y.bm.toFixed(2):"â"}),e.jsx("td",{className:`py-2.5 text-right text-xs ${i(y.diffBm)}`,children:h(y.diffBm)}),e.jsx("td",{className:"py-2.5 text-right text-slate-500",children:y.sm!=null?y.sm.toFixed(2):"â"}),e.jsx("td",{className:`py-2.5 text-right text-xs ${i(y.diffSm)}`,children:h(y.diffSm)}),e.jsx("td",{className:`py-2.5 text-right ${v(y.rank?.rank,y.rank?.total)}`,children:y.rank?`#${y.rank.rank}/${y.rank.total}`:"â"})]},L))})]}),p&&e.jsx("p",{className:"mt-4 text-xs text-slate-500 leading-relaxed border-t border-slate-100 pt-3",children:p})]})]})}function Ni({data:t}){const[s,a]=b.useState("pct"),n=t,r=b.useMemo(()=>{const d={};for(const c of n.trend){d[c.quarter]||(d[c.quarter]={quarter:Be(c.quarter),_raw:c.quarter,_nurseAg:0,_nurseTot:0});const m=d[c.quarter];s==="pct"?m[c.role_group]=c.agency_pct:(m[`${c.role_group}_agency`]=c.agency_hours,m[`${c.role_group}_employee`]=c.employee_hours),(c.role_group==="rn"||c.role_group==="lpn"||c.role_group==="cna")&&(m._nurseAg+=Number(c.agency_hours)||0,m._nurseTot+=(Number(c.agency_hours)||0)+(Number(c.employee_hours)||0))}return Object.values(d).map(c=>({...c,total_nursing_agency_pct:c._nurseTot>0?+(c._nurseAg/c._nurseTot*100).toFixed(1):null})).sort((c,m)=>c._raw.localeCompare(m._raw))},[n.trend,s]),l=["cna","lpn","rn","leadership","social_work"],o=d=>d==="total_nursing_agency_pct"?"Total Nursing Agency":nt[d]||d;return e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"section-heading flex items-center gap-2",children:[e.jsx(Vs,{size:14,className:"text-slate-400"}),"Agency Utilization Trend"]}),e.jsx("div",{className:"flex gap-1",children:["pct","hours"].map(d=>e.jsx("button",{onClick:()=>a(d),className:`px-3 py-1 text-xs rounded-md ${s===d?"bg-sky-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,children:d==="pct"?"Agency %":"Hours"},d))})]}),n.state_avg_agency_pct!=null&&e.jsxs("p",{className:"text-xs text-slate-400",children:["State average nursing agency: ",e.jsxs("strong",{className:"text-slate-600",children:[n.state_avg_agency_pct,"%"]})]}),e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:e.jsx(je,{width:"100%",height:320,children:s==="pct"?e.jsxs(Dn,{data:r,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"quarter",tick:{fontSize:11,fill:"#64748b"}}),e.jsx(xe,{tick:{fontSize:11,fill:"#64748b"},tickFormatter:d=>`${Math.round(d)}%`,domain:[0,d=>Math.ceil(Math.max(10,d)/5)*5]}),e.jsx(ce,{contentStyle:{fontSize:12,borderRadius:8,border:"1px solid #e2e8f0"},formatter:(d,c)=>[`${d}%`,o(c)]}),e.jsx(Fe,{formatter:o,wrapperStyle:{fontSize:11}}),l.map(d=>e.jsx(Tn,{type:"monotone",dataKey:d,stackId:"1",fill:Re[d],stroke:
1Re[d],fillOpacity:.45},d)),e.jsx(oe,{type:"monotone",dataKey:"total_nursing_agency_pct",name:"total_nursing_agency_pct",stroke:"#0f172a",strokeWidth:2.5,dot:{r:2.5,fill:"#0f172a"},activeDot:{r:4}})]}):e.jsxs(it,{data:r,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"quarter",tick:{fontSize:11,fill:"#64748b"}}),e.jsx(xe,{tick:{fontSize:11,fill:"#64748b"}}),e.jsx(ce,{contentStyle:{fontSize:12,borderRadius:8,border:"1px solid #e2e8f0"},formatter:(d,c)=>{const[m,p]=c.split("_");return[d.toLocaleString()+" hrs",`${nt[m]||m} (${p})`]}}),e.jsx(Fe,{formatter:d=>{const[c,m]=d.split("_");return`${nt[c]||c} (${m})`},wrapperStyle:{fontSize:11}}),l.map(d=>e.jsx(_e,{dataKey:`${d}_agency`,stackId:"1",fill:Re[d],fillOpacity:.9},`${d}_agency`))]})})})]})}function wi({data:t,ccn:s}){const[a,n]=b.useState(null),[r,l]=b.useState(!1),[o,d]=b.useState(!1),[c,m]=b.useState(!1),p=["rn","lpn","cna"],i=ee({queryKey:["staffing-tenure",s,a],queryFn:()=>qt(s,{quarter:a}),enabled:!!a}),h=a&&i.data||t,v=(h.distributions||[]).filter(S=>p.includes(S.role_group)),y=h.quarters||[],L=h.quarter,D=hi(a||L,y),j=ee({queryKey:["staffing-tenure",s,D],queryFn:()=>qt(s,{quarter:D}),enabled:o&&!!D}),M=a||L,f=ee({queryKey:["staffing-tenure-benchmark",s,M],queryFn:()=>Va(s,{quarter:M}),enabled:c}),w=b.useMemo(()=>{let S=0,C=0,u=0;for(const g of v)S+=g.total_employees,C+=g.censored_count,g.avg_tenure_days!=null&&(u+=g.avg_tenure_days*g.total_employees);return{total:S,censored:C,avgDays:S>0?Math.round(u/S):null}},[v]),B=b.useMemo(()=>{if(!v.length)return[];const S=v[0].buckets.map(x=>x.bucket),C=w.total||1,u=o&&j.data?j.data.distributions.filter(x=>p.includes(x.role_group)):[],g=u.reduce((x,P)=>x+P.total_employees,0)||1,A=c&&f.data?f.data.benchmark.buckets:null;return S.map(x=>{const P={bucket:x};if(r){for(const $ of v){const T=$.buckets.find(F=>F.bucket===x);P[$.role_group]=T?T.pct:0}if(o)for(const $ of u){const T=$.buckets.find(F=>F.bucket===x);P[`${$.role_group}_prior`]=T?T.pct:0}}else{let $=0;for(const T of v){const F=T.buckets.find(R=>R.bucket===x);$+=F?F.count:0}if(P.all_nursing=Math.round(100*$/C*10)/10,o&&u.length){let T=0;for(const F of u){const R=F.buckets.find(V=>V.bucket===x);T+=R?R.count:0}P.prior_year=Math.round(100*T/g*10)/10}}if(A){const $=A.find(T=>T.bucket===x);$&&(P.state_avg=$.pct)}return P})},[v,r,o,j.data,c,f.data,w.total]),z=S=>{if(S==="all_nursing")return`All Nursing (${Be(a||L)})`;if(S==="prior_year")return`Prior Year (${Be(D)})`;if(S==="state_avg")return`${f.data?.state||"State"} Avg (${f.data?.facility_count||"?"} facilities)`;if(S.endsWith("_prior")){const C=S.replace("_prior","");return`${nt[C]||C} (${Be(D)})`}return nt[S]||S},_=S=>`px-3 py-1 text-xs rounded-md ${S?"bg-sky-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`;return e.jsxs("section",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("h2",{className:"section-heading flex items-center gap-2",children:[e.jsx(Hs,{size:14,className:"text-slate-400"}),"Nursing Staff Tenure Distribution",e.jsx(le,{text:"Tenure of direct (non-agency) nursing employees active in the selected quarter. Tenure = time from first to last work date across all PBJ data. Left-censored employees present in Q2 2020 may have longer actual tenure."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("button",{onClick:()=>l(!r),className:_(r),children:"By Role"}),D&&e.jsx("button",{onClick:()=>d(!o),className:_(o),children:"vs Prior Year"}),e.jsx("button",{onClick:()=>m(!c),className:_(c),children:"vs State Avg"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("label",{className:"text-[10px] text-slate-400",children:"Quarter:"}),e.jsx("select",{value:a||L||"",onChange:S=>n(S.target.value||null),className:"text-xs border border-slate-200 rounded px-2 py-1 text-slate-600",children:y.slice(-4).map(S=>e.jsxs("option",{value:S,children:[Be(S),S===y[y.length-1]?" (latest)":""]},S))})]})]})]}),e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm px-4 py-3",children:r?e.jsx("div",{className:"flex items-stretch gap-6 flex-wrap",children:v.map((S,C)=>e.jsxs("div",{className:`flex items-center gap-4 ${C>0?"border-l border-slate-100 pl-6":""}`,children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:nt[S.role_group]||S.role_group}),e.jsx("p",{className:"text-xl font-bold text-slate-900 tabular-nums leading-tight",children:S.total_employees})]}),e.jsxs("div",{className:"text-[10px] text-slate-500 leading-tight tabular-nums",children:[e.jsxs("div",{children:["Avg ",e.jsx("span",{className:"text-slate-700",children:ke(S.avg_tenure_days)})]}),e.jsxs("div",{children:["Med ",e.jsx("span",{className:"text-slate-700",children:ke(S.median_tenure_days)})]}),S.censored_count>0&&e.jsxs("div",{className:"text-slate-400",children:[S.censored_count," censored"]})]})]},S.role_group))}):e.jsxs("div",{className:"flex items-center gap-6 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"Total Nursing Staff"}),e.jsx("p",{className:"text-xl font-bold text-slate-900 tabular-nums",children:w.total})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"Avg Tenure"}),e.jsx("p",{className:"text-xl font-bold text-slate-900 tabular-nums",children:ke(w.avgDays)})]}),w.censored>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"Left-censored"}),e.jsx("p",{className:"text-xl font-bold text-slate-500 tabular-nums",children:w.
1censored})]}),o&&j.data&&e.jsxs("div",{className:"border-l border-slate-200 pl-6",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"Prior Year Total"}),e.jsx("p",{className:"text-xl font-bold text-slate-500 tabular-nums",children:j.data.distributions.filter(S=>p.includes(S.role_group)).reduce((S,C)=>S+C.total_employees,0)})]}),c&&f.data&&e.jsxs("div",{className:"border-l border-slate-200 pl-6",children:[e.jsxs("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:[f.data.state," Avg Tenure"]}),e.jsx("p",{className:"text-xl font-bold text-slate-500 tabular-nums",children:ke(f.data.benchmark.avg_tenure_days)}),e.jsxs("p",{className:"text-[9px] text-slate-400",children:[f.data.facility_count," facilities"]})]})]})}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsx(je,{width:"100%",height:300,children:e.jsxs(it,{data:B,margin:{top:28,right:8,left:0,bottom:0},children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"bucket",tick:{fontSize:10,fill:"#64748b"}}),e.jsx(xe,{tick:{fontSize:11,fill:"#64748b"},unit:"%",domain:[0,S=>Math.ceil((S||0)*1.1/5)*5]}),e.jsx(ce,{contentStyle:{fontSize:12,borderRadius:8,border:"1px solid #e2e8f0"},formatter:(S,C)=>[`${S}%`,z(C)]}),e.jsx(Fe,{formatter:z,wrapperStyle:{fontSize:11}}),r?e.jsxs(e.Fragment,{children:[v.map(S=>e.jsx(_e,{dataKey:S.role_group,fill:Re[S.role_group]||"#94a3b8",fillOpacity:.85,label:{position:"top",fontSize:9,fill:"#64748b",formatter:C=>C>0?`${C}%`:""}},S.role_group)),o&&v.map(S=>e.jsx(_e,{dataKey:`${S.role_group}_prior`,fill:Re[S.role_group]||"#94a3b8",fillOpacity:.3},`${S.role_group}_prior`))]}):e.jsxs(e.Fragment,{children:[e.jsx(_e,{dataKey:"all_nursing",fill:Re.rn,fillOpacity:.85,name:"all_nursing",label:{position:"top",fontSize:9,fill:"#64748b",formatter:S=>S>0?`${S}%`:""}}),o&&e.jsx(_e,{dataKey:"prior_year",fill:"#cbd5e1",fillOpacity:.7,name:"prior_year"})]}),c&&f.data&&e.jsx(_e,{dataKey:"state_avg",fill:"#94a3b8",fillOpacity:.5,name:"state_avg",label:{position:"top",fontSize:9,fill:"#64748b",formatter:S=>S>0?`${S}%`:""}})]})}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-2 italic",children:"Direct employees only â excludes agency / contract staff"})]})]})}const ki={1:"#475569",5:"#334155",6:"#0284c7",7:"#0ea5e9",8:"#64748b",9:"#94a3b8",10:"#475569",11:"#64748b",12:"#94a3b8",14:"#0369a1",30:"#cbd5e1",31:"#cbd5e1"};function Si({h:t,minDate:s,maxDate:a,totalDays:n}){const[r,l]=b.useState(!1),o=t.first_date?new Date(t.first_date):s,d=t.last_date?new Date(t.last_date):a,c=o<s?s:o,m=d>a?a:d,p=(c-s)/Mt,i=(m-s)/Mt,h=p/n*100,v=Math.max(.5,(i-p)/n*100),y=ki[t.job_code]||"#94a3b8",L=t.still_active,D=h>55;return e.jsxs("div",{className:"relative h-7",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsx("div",{className:`absolute h-5 top-1 rounded-md transition-all ${L?"ring-2 ring-sky-400 ring-offset-1":""}`,style:{left:`${h}%`,width:`${v}%`,backgroundColor:y,opacity:t.left_censored?.45:.85},children:v>8&&e.jsx("span",{className:"absolute inset-0 flex items-center justify-center text-[9px] text-white font-medium truncate px-1",children:ke(t.tenure_days)})}),r&&e.jsxs("div",{className:"absolute z-20 bg-slate-800 text-white text-[10px] rounded-lg px-3 py-2 shadow-lg whitespace-nowrap pointer-events-none",style:{bottom:"100%",marginBottom:"2px",...D?{right:`${Math.max(0,100-h-v)}%`}:{left:`${h}%`}},children:[e.jsxs("span",{className:"font-semibold",children:["ID ***",String(t.employee_id).slice(-4)]})," ",t.first_date," to ",t.last_date||"present"," ","(",ke(t.tenure_days),")",t.left_censored&&e.jsx("span",{className:"text-amber-300 ml-1",children:"*may predate data"}),t.gap_from_previous_days!=null&&e.jsxs("span",{className:"text-sky-300 ml-1",children:[t.gap_from_previous_days,"d gap"]})]})]})}function Ci({data:t,ccn:s}){const[a,n]=b.useState("leadership"),[r,l]=b.useState(30),[o,d]=b.useState("2024_1"),[c,m]=b.useState(null),p=ee({queryKey:["staffing-turnover",s,a],queryFn:()=>Qs(s,{role:a}),enabled:a!=="leadership"}),i=a!=="leadership"&&p.isLoading,h=a==="leadership"?t:p.data||null,v=b.useMemo(()=>{const u=h?.holders||[];return r<=0?u:u.filter(g=>g.tenure_days==null||g.tenure_days>=r)},[h?.holders,r]),y=(h?.holders||[]).length-v.length,L=b.useMemo(()=>{const u=h?.holders||[];if(!u.length)return[];const g=u.flatMap(T=>
1[T.first_date,T.last_date].filter(Boolean)).map(T=>new Date(T));if(!g.length)return[];const A=new Date(Math.min(...g)),x=new Date(Math.max(...g)),P=`${A.getFullYear()}_${Math.ceil((A.getMonth()+1)/3)}`,$=`${x.getFullYear()}_${Math.ceil((x.getMonth()+1)/3)}`;return pi(P,$).reverse()},[h?.holders]),D=o?mi(o):null,j=c?ui(c):null,M=b.useMemo(()=>!D&&!j?v:v.filter(u=>{const g=u.first_date?new Date(u.first_date):new Date("2000-01-01"),A=u.last_date?new Date(u.last_date):new Date;return!(D&&A<D||j&&g>j)}),[v,D,j]),f=M.flatMap(u=>[u.first_date,u.last_date].filter(Boolean)).map(u=>new Date(u)),w=f.length?new Date(Math.min(...f)):new Date("2020-01-01"),B=f.length?new Date(Math.max(...f)):new Date,z=D||w,_=j||B,S=Math.max(1,(_-z)/Mt),C={};for(const u of M){const g=u.job_code;C[g]||(C[g]=[]),C[g].push(u)}return e.jsx("section",{className:"space-y-3",children:e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4 space-y-3",children:[e.jsxs("h2",{className:"section-heading flex items-center gap-2",children:[e.jsx(Ia,{size:14,className:"text-slate-400"}),"Leadership & Role Timeline",t?.total_transitions>0&&e.jsxs("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-slate-100 text-slate-600 border border-slate-200 font-normal normal-case tracking-normal",children:[t.total_transitions," transition",t.total_transitions!==1?"s":""]})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("label",{className:"text-[10px] text-slate-400",children:["Range ",e.jsx(le,{text:"Filter the timeline to a specific date range. Only employees whose tenure overlaps the selected range are shown. Bars are clipped to the visible window.",size:10})]}),e.jsxs("select",{value:o||"",onChange:u=>d(u.target.value||null),className:"text-xs border border-slate-200 rounded px-1.5 py-0.5 text-slate-600",children:[e.jsx("option",{value:"",children:"Earliest"}),L.map(u=>e.jsx("option",{value:u,children:Be(u)},u))]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"to"}),e.jsxs("select",{value:c||"",onChange:u=>m(u.target.value||null),className:"text-xs border border-slate-200 rounded px-1.5 py-0.5 text-slate-600",children:[e.jsx("option",{value:"",children:"Latest"}),L.map(u=>e.jsx("option",{value:u,children:Be(u)},u))]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("label",{className:"text-[10px] text-slate-400",children:["Min tenure ",e.jsx(le,{text:"Hide short stints (e.g. temporary admins). Bars shorter than this threshold are hidden from the timeline.",size:10})]}),e.jsxs("select",{value:r,onChange:u=>l(Number(u.target.value)),className:"text-xs border border-slate-200 rounded px-1.5 py-0.5 text-slate-600",children:[e.jsx("option",{value:0,children:"Show all"}),e.jsx("option",{value:7,children:"7+ days"}),e.jsx("option",{value:14,children:"14+ days"}),e.jsx("option",{value:30,children:"30+ days"}),e.jsx("option",{value:60,children:"60+ days"}),e.jsx("option",{value:90,children:"90+ days"})]}),y>0&&e.jsxs("span",{className:"text-[10px] text-slate-400",children:["(",y," hidden)"]})]}),e.jsx("div",{className:"flex gap-1",children:[["leadership","Leadership"],["nurse_admin","Nurses w/ Admin"],["social_services","Social Services"]].map(([u,g])=>e.jsx("button",{onClick:()=>n(u),className:`px-3 py-1 text-xs rounded-md ${a===u?"bg-sky-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"}`,children:g},u))})]}),h?.avg_tenure_days!=null&&e.jsxs("div",{className:"flex gap-4 text-xs text-slate-500",children:[e.jsxs("span",{children:["Avg tenure: ",e.jsx("strong",{className:"text-slate-700 tabular-nums",children:ke(h.avg_tenure_days)})]}),e.jsxs("span",{children:["Transitions: ",e.jsx("strong",{className:"text-slate-700 tabular-nums",children:h.total_transitions})]})]}),e.jsx("div",{className:"overflow-x-auto",children:i?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(ge,{className:"animate-spin text-sky-400",size:24})}):M.length===0?e.jsxs("p",{className:"text-sm text-slate-400 text-center py-8",children:["No data for selected role",r>0?" (try lowering the min tenure filter)":"","."]}):e.jsxs("div",{className:"min-w-[600px]",children:[e.jsx("div",{className:"relative h-6 mb-1 border-b border-slate-100",children:Mi(z,_,S).map(({label:u,pct:g})=>e.jsx("span",{className:"absolute text-[10px] text-slate-400 -translate-x-1/2",style:{left:`${Math.max(2,Math.min(98,g))}%`},children:u},u))}),Object.entries(C).sort((u,g)=>
1Number(u[0])-Number(g[0])).map(([u,g])=>e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-medium text-slate-500 mb-0.5",children:xi[u]||`Code ${u}`}),g.map((A,x)=>e.jsx(Si,{h:A,minDate:z,maxDate:_,totalDays:S},x))]},u)),e.jsxs("div",{className:"flex items-center gap-4 mt-3 pt-2 border-t border-slate-100 text-[10px] text-slate-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded ring-2 ring-sky-400",style:{backgroundColor:"#475569"}}),"Active"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded opacity-50",style:{backgroundColor:"#475569"}}),"Left-censored (may predate Q2 2020)"]}),t.total_transitions>0&&e.jsxs("span",{className:"ml-auto text-slate-500 font-medium",children:[t.total_transitions," transition",t.total_transitions!==1?"s":""," detected"]})]})]})})]})})}function Mi(t,s,a){const n=[],r=t.getFullYear(),l=s.getFullYear();for(let o=r;o<=l;o++){const m=(new Date(o,0,1)-t)/Mt/a*100;m>=0&&m<=100&&n.push({label:String(o),pct:m})}return n}const js=t=>{if(t==null||t==="")return"";if(typeof t!="number")return t;const s=Math.abs(t),a=Number.isInteger(t)?s.toLocaleString():s<1e3?Number(s.toFixed(4)).toLocaleString(void 0,{maximumFractionDigits:4}):Math.round(s).toLocaleString();return t<0?`(${a})`:a};function $i({ccn:t,fyYear:s}){const[a,n]=b.useState(s||null),[r,l]=b.useState(null),[o,d]=b.useState(!1),c=De(()=>d(!1),{enabled:o}),{data:m,isLoading:p}=ee({queryKey:["costreport-index",t,a],queryFn:()=>Qa(t,a),enabled:!!t,staleTime:300*1e3}),i=m?.worksheets||[],h=m?.years||[],v=r||i[0]?.code,{data:y,isLoading:L,isError:D}=ee({queryKey:["costreport-ws",t,v,a],queryFn:()=>Ya(t,v,a),enabled:!!t&&!!v,staleTime:300*1e3}),j=y?.columns||[],M=y?.rows||[],f=!!y?.form_version&&y.form_version!=="2540-24",w=u=>u.length===7&&/[A-Z]/.test(u[5])?u.slice(0,5)+"00":u,B=u=>u?i.some(g=>g.code===u)?u:i.find(g=>w(g.code)===u)?.code||null:null,z=u=>i.find(g=>g.code===u)?.title||u,_=new Set(j.filter(u=>u.subtotal||/subtotal|trial balance|net expenses|^total$|cost.?to.?charge|\bratios?\b/i.test(u.label||"")).map(u=>u.num)),S=()=>{const g=[["Code","Description",...j.map($=>$.label)].map($=>`"${($||"").replace(/"/g,'""')}"`).join(",")];for(const $ of M){const T=j.map(F=>{const R=$.cells[F.num];return R==null?"":typeof R=="number"?R:`"${String(R).replace(/"/g,'""')}"`});g.push([`"${$.code}"`,`"${($.label||"").replace(/"/g,'""')}"`,...T].join(","))}const A=new Blob([g.join(` 2`)],{type:"text/csv"}),x=URL.createObjectURL(A),P=document.createElement("a");P.href=x,P.download=`costreport_${t}_${y?.fy_year||a}_${v}.csv`,P.click(),URL.revokeObjectURL(x)},C=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Fiscal year"}),e.jsxs("select",{value:a??"",onChange:u=>{n(u.target.value?Number(u.target.value):null)},className:"text-xs border border-slate-200 rounded-md px-2 py-1 bg-white text-slate-700",children:[!a&&e.jsx("option",{value:"",children:"Latest"}),h.map(u=>e.jsxs("option",{value:u,children:["FY",u]},u))]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Worksheet"}),e.jsx("select",{value:v||"",onChange:u=>l(u.target.value),className:"text-xs border border-slate-200 rounded-md px-2 py-1 bg-white text-slate-700 max-w-[22rem]",children:i.map(u=>e.jsx("option",{value:u.code,children:u.title},u.code))})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[M.length>0&&e.jsxs("button",{onClick:S,className:"flex items-center gap-1.5 text-xs text-slate-600 hover:text-sky-600 transition-colors",children:[e.jsx(Ue,{size:13})," Export CSV"]}),!o&&e.jsxs("button",{onClick:()=>d(!0),className:"flex items-center gap-1.5 text-xs text-slate-600 hover:text-sky-600 transition-colors",title:"Open full screen â these grids are wide",children:[e.jsx(ft,{size:13})," Expand"]})]})]}),(p||L)&&e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(ge,{className:"animate-spin text-sky-500",size:20})}),D&&e.jsx("div",{className:"text-sm text-red-500 py-8 text-center",children:"Could not load this worksheet for the selected year."}),!L&&!D&&y&&e.jsxs(e.Fragment,{children:[(y.note||f)&&e.jsxs("div",{className:"flex items-start gap-2 bg-slate-50 border border-slate-200 rounded-lg px-3 py-2.5 mb-3",children:[e.jsx(Ye,{size:14,className:"text-slate-400 shrink-0 mt-0.5"}),e.jsxs("p",{className:"text-xs text-slate-600 leading-relaxed",children:[y.note,f&&e.jsxs("span",{className:"text-slate-500",children:[" ","This FY",y.fy_year," report uses the earlier CMS-",y.form_version," form, which CMS replaced for FY2025. Its layout differs, so some worksheets aren't fully captioned yet â figures are unaffected."]})]})]}),e.jsx("div",{className:`overflow-auto border border-slate-200 rounded-lg ${o?"min-h-0 flex-1":"max-h-[70vh]"}`,children:e.jsxs("table",{className:"text-xs tabular-nums min-w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50 text-slate-500",children:[e.jsx("th",{className:"text-left px-2 py-2 font-semibold sticky top-0 left-0 z-20 bg-slate-50 border-b border-slate-200 whitespace-nowrap",children:"Line"}),e.jsx("th",{className:"text-left px-2 py-2 font-semibold sticky top-0 left-10 z-20 bg-slate-50 border-b border-slate-200 whitespace-nowrap min-w-[200px]",children:"Description"}),j.map(u=>
2e.jsx("th",{className:`text-right align-bottom px-2.5 py-2 font-semibold leading-tight max-w-[7rem] sticky top-0 z-10 border-b border-slate-200 ${_.has(u.num)?"bg-slate-100 text-slate-600":"bg-slate-50"}`,children:u.label},u.num))]})}),e.jsx("tbody",{className:"text-slate-800",children:M.map(u=>{const g=u.total||/^(total|net |subtotal|grand)/i.test(u.label||""),A=g?"bg-slate-100":"bg-white";return e.jsxs("tr",{className:`hover:bg-sky-50/40 ${g?"font-semibold text-slate-900 border-y border-slate-300":"border-b border-slate-50"}`,children:[e.jsx("td",{className:`px-2 py-1.5 sticky left-0 whitespace-nowrap ${A} ${g?"text-slate-500":"text-slate-400"}`,children:u.code}),e.jsx("td",{className:`px-2 py-1.5 sticky left-10 whitespace-nowrap ${A} ${g?"":"font-medium text-slate-700"}`,children:u.label||e.jsx("span",{className:"text-slate-300",children:"â"})}),j.map((x,P)=>{if(u.closed_after!=null&&P>u.closed_after)return e.jsx("td",{className:"px-2.5 py-1.5 bg-slate-100",title:"Closed on step-down â this cost center is allocated before the ones to the right, so it receives nothing from them."},x.num);const $=u.cells[x.num],T=typeof $=="number",F=T&&$!==0?B(u.links?.[x.num]||u.link||x.link):null,R=u.closed_after!=null&&P===u.closed_after,V=R?"bg-sky-50/70 border-x border-sky-100":g?"bg-slate-100":_.has(x.num)?"bg-slate-50 font-medium":"";return e.jsx("td",{className:`px-2.5 py-1.5 ${T?"text-right":"text-left text-slate-600"} ${V} ${R?"font-semibold text-slate-900":""} ${T&&$===0?"text-slate-300":""} ${T&&$<0?"text-red-600":""}`,title:R?"Accumulated cost â the total allocated into this cost center, and the amount it allocates out before closing.":void 0,children:F?e.jsx("button",{onClick:()=>l(F),className:"text-sky-600 hover:underline",title:`See the detail behind this figure â ${z(F)}`,children:js($)}):js($)},x.num)})]},u.line)})})]})})]}),e.jsxs("p",{className:"text-[11px] text-slate-400 mt-2",children:[y?.title," · straight from the filed CMS cost report",y?.form_version?` (Form ${y.form_version})`:"",". Row descriptions are the facility's own cost-center labels; blank cells were not reported."]})]});return o?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-3",onClick:()=>d(!1),children:e.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-labelledby":"costreport-expanded-title",className:"flex max-h-[96vh] min-w-[36rem] max-w-[98vw] flex-col rounded-xl bg-white p-5 shadow-xl",onClick:u=>u.stopPropagation(),children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{id:"costreport-expanded-title",className:"text-sm font-semibold text-slate-800",children:["Cost Report Worksheets · CCN ",t]}),e.jsx(ts,{onClick:()=>d(!1),label:"Close full screen"})]}),C]})}):e.jsx("div",{className:"p-5",children:C})}const at=t=>t!=null?`$${(t/1e6).toFixed(1)}M`:"--",st=t=>t!=null?`$${Math.round(t/1e3).toLocaleString()}K`:"--",we=t=>t!=null?`$${t.toFixed(0)}`:"--",vs=t=>t!=null?`${t.toFixed(0)}`:"--",Ns=t=>t!=null?t.toLocaleString():"--",vt={Medicare:"#64748b",Medicaid:"#94a3b8",Other:"#cbd5e1"};function Fi({lines:t,totalRevenue:s,nonOp:a}){if(!t?.length||!a||!s)return null;const n=Math.abs(a)/s;return e.jsxs("span",{className:"relative inline-block group",children:[e.jsxs("span",{className:"text-slate-500 underline decoration-dotted decoration-slate-300 cursor-help",children:["non-op ",n>=.1?`${(n*100).toFixed(0)}%`:"detail"]}),e.jsxs("span",{className:`pointer-events-none absolute z-[5000] right-0 top-full mt-1.5\r 3 w-80 px-3 py-2.5 rounded-lg bg-slate-800 text-[11px] text-slate-100 shadow-lg\r 4 opacity-0 group-hover:opacity-100 transition-opacity duration-150`,children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-slate-300 mb-1.5",children:"Non-operating income â G-3 lines"}),e.jsx("div",{className:"space-y-1",children:t.map((r,l)=>e.jsxs("div",{className:"flex justify-between gap-3 leading-snug",children:[e.jsx("span",{className:"text-slate-200 truncate",title:r.label||`Line ${r.line_num}`,children:r.label||e.jsxs("span",{className:"italic text-slate-400",children:["Line ",r.line_num," (unlabeled)"]})}),e.jsxs("span",{className:`font-mono shrink-0 ${r.amount<0?"text-red-300":"text-emerald-200"}
4`,children:["$",Math.round(r.amount).toLocaleString()]})]},l))}),e.jsxs("div",{className:"mt-2 pt-1.5 border-t border-slate-700 flex justify-between text-[10px] text-slate-300",children:[e.jsx("span",{children:"Total non-op"}),e.jsxs("span",{className:"font-mono",children:["$",Math.round(a).toLocaleString()]})]}),e.jsx("div",{className:"mt-1 text-[10px] text-slate-400 italic leading-snug",children:"Self-reported on Worksheet G-3. Labels are facility-supplied free text."})]})]})}function Ai({peerRank:t,peers:s,metricKey:a,lowerBetter:n=!1,formatter:r,label:l,currentCcn:o}){const[d,c]=b.useState(!1),m=b.useRef(null);if(b.useEffect(()=>{if(!d)return;const i=h=>{m.current&&!m.current.contains(h.target)&&c(!1)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[d]),!t?.rank||!t?.total)return null;const p=(s||[]).filter(i=>i[a]!=null).slice().sort((i,h)=>n?i[a]-h[a]:h[a]-i[a]);return e.jsxs("div",{className:"relative inline-block",ref:m,children:[e.jsxs("button",{onClick:i=>{i.stopPropagation(),c(!d)},className:"text-[10px] text-slate-500 hover:text-sky-600 hover:underline cursor-pointer",title:"Click to see nearby peer ranking",children:[e.jsxs("span",{className:"font-semibold",children:["#",t.rank]}),e.jsxs("span",{className:"text-slate-400",children:[" of ",t.total," nearby"]})]}),d&&p.length>0&&e.jsxs("div",{className:"absolute z-50 right-0 top-full mt-1 bg-white border border-slate-200 rounded-lg shadow-xl p-2 w-72 max-w-[calc(100vw-1.5rem)] max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-slate-500 px-2 py-1 uppercase tracking-wide",children:[l," â Nearby SNFs"]}),e.jsx("div",{className:"divide-y divide-slate-100",children:p.map((i,h)=>e.jsxs("div",{className:`flex justify-between items-center px-2 py-1.5 text-xs rounded ${i.ccn===o?"bg-sky-50 font-semibold":""}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-slate-400 w-4 text-right shrink-0",children:h+1}),e.jsx(lt,{to:`/facility/${i.ccn}`,onClick:v=>v.stopPropagation(),className:"truncate text-slate-700 hover:text-sky-600",children:i.provider_name}),i.dist!=null&&i.dist>0&&e.jsxs("span",{className:"text-slate-400 shrink-0",children:["(",i.dist,"mi)"]})]}),e.jsx("span",{className:"text-slate-600 shrink-0 ml-2",children:r(i[a])})]},i.ccn))})]})]})}function We({label:t,value:s,sub:a,tip:n,color:r,rank:l,total:o,badge:d}){return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 p-4 shadow-sm min-w-0",children:[e.jsxs("p",{className:"text-[10px] text-slate-500 uppercase font-medium tracking-wide flex items-center gap-1",children:[t," ",n&&e.jsx(le,{text:n,size:10,position:"below"})]}),e.jsx("p",{className:`text-xl font-bold mt-1 truncate ${r||"text-slate-800"}`,children:s}),(a||d)&&e.jsxs("div",{className:"text-[10px] text-slate-500 mt-0.5 flex items-center min-w-0",children:[a&&e.jsx("span",{className:"truncate",children:a}),a&&d&&e.jsx("span",{className:"mx-1 text-slate-300 shrink-0",children:"·"}),d&&e.jsx("span",{className:"shrink-0",children:d})]}),l&&o&&e.jsxs("p",{className:"text-[10px] font-medium text-sky-600 mt-0.5",children:["#",l," of ",o]})]})}function Pi({label:t,facility:s,p25:a,median:n,p75:r,rank:l,total:o,higherBetter:d=!0,format:c=pe,peerRankBadge:m}){if(s==null&&n==null)return null;const p=s!=null&&n!=null&&(d?s>=n:s<=n);return e.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-slate-50 last:border-0",children:[e.jsx("span",{className:"w-36 text-xs text-slate-600 text-right truncate",children:t}),e.jsx("span",{className:`w-16 text-xs font-bold text-right ${p?"text-sky-600":"text-slate-800"}`,children:c(s)}),e.jsx("span",{className:"w-12 text-[10px] text-slate-500 text-right",children:c(a)}),e.jsx("span",{className:"w-12 text-[10px] font-medium text-slate-600 text-right",children:c(n)}),e.jsx("span",{className:"w-12 text-[10px] text-slate-500 text-right",children:c(r)}),l&&o?e.jsxs("span",{className:"w-16 text-[10px] text-sky-600 font-medium text-right",children:["#",l,"/",o]}):e.jsx("span",{className:"w-16"}),e.jsx("span",{className:"w-24 text-right",children:m||null})]})}function Ri({nl:t}){const s=t?.total,a=s?.emp_hours||0,n=s?.con_hours||0;if(!s||a+n===0)return null;const r=s.agency_hours_pct??0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-0.5 mb-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-wide text-slate-400 mr-1",children:"Nursing â employee vs. agency"}),e.jsx("span",{className:"text-lg font-bold tabular-nums text-slate-800",children:pe(r)}),e.jsx("span",{className:"text-[11px] text-slate-500",children:"of hours agency"}),t.agency_cost!=null&&e.jsxs("span",{className:"text-[11px] text-slate-500 tabular-nums",children:["· ",st(t.agency_cost)," spend (",pe(t.agency_cost_pct)," of nursing cost)"]})]}),e.jsxs("div",{className:"h-1.5 rounded-full overflow-hidden flex bg-slate-100",children:[e.jsx("div",{className:"h-full bg-slate-300",style:{width:`${100-r}%`}}),e.jsx("div",{className:"h-full bg-slate-600",style:{width:`${r}%`}})]})]})}function Di({ccn:t}){const[s,a]=b.useState(null),[n,r]=b.useState("snapshot"),{data:l,isLoading:o,isError:d,error:c}=ee({queryKey:["facility-financial",t,s],queryFn:()=>Ua(t,s?{fy_year:s}:{}),enabled:!!t,retry:(N,Y)=>!Y?.upgrade&&N<2});if(o)return e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(ge,{className:"animate-spin text-sky-500",size:24})});if(d)return e.jsx(Br,{error:c});const m=l?.history||[],p=m.map(N=>N.fy_year),i=l?.latest;if(!i)return e.jsxs("div",{className:"text-center py-16 text-slate-400",children:[e.jsx(Ga,{size:24,className:"mx-auto mb-2 text-slate-300"}),e.jsx("p",{className:"text-lg font-medium",children:"No cost report data available"}),e.jsx("p",{className:"text-sm mt-1",children:"CMS cost report data for this facility has not been filed or processed yet."})]});const h=l.benchmarks||[],v=Object.fromEntries(h.map(N=>[N.metric,N])),y=l.dept_benchmarks||[],L=(l.labor_detail||[]).filter(N=>N.total>0&&N.role!=="Total Nursing"),D=i.nursing_labor?L.filter(N=>!["RN","LPN","CNA/Aide"].includes(N.role)):L,j=Object.fromEntries((l.labor_detail||[]).map(N=>[N.role,N])),M={RN:"RN",LPN:"LPN",CNA:"CNA/Aide"},f=D.filter(N=>{if(N.role==="Nursing Admin")return!1;const Y=["Admin & General","Plant Ops","Central Supply","Medical Records"];return!((N.contract_pct||0)>=100&&Y.includes(N.role))}),w=N=>({key:"o-"+N.role,role:N.role,section:i.nursing_labor?"Other departments":null,emp:(N.contract_pct||0)>=100?null:N.hourly_rate,agency:null,premium:null,contractPct:N.contract_pct,median:N.state_median_rate,rank:N.state_rank,total:N.state_total}),B=i.nursing_labor?[...(i.nursing_labor.roles||[]).map(N=>{const Y=j[M[N.role]||N.role];return{key:"n-"+N.role,role:N.role,section:"Nursing",emp:N.emp_wage,agency:N.con_wage,premium:N.premium_pct,contractPct:N.agency_hours_pct,median:Y?.state_median_rate,rank:Y?.state_rank,total:Y?.state_total}}),...f.map(w)]:f.map(w),z=B.some(N=>N.agency!=null||N.premium!=null),_=z?7:5,S=(()=>
4{if(i.fy_start&&i.fy_end){const N=Math.round((new Date(i.fy_end)-new Date(i.fy_start))/864e5)+1;if(N>0&&N<800)return N}return 365})(),C=N=>N!=null&&S?N/S:null,u=[{name:"Medicare",value:i.medicare_day_pct,adc:C(i.medicare_days)},{name:"Medicaid",value:i.medicaid_day_pct,adc:C(i.medicaid_days)},{name:"Other",value:i.other_day_pct,adc:C(i.other_days)}].filter(N=>N.value!=null&&N.value>0),g=C(i.total_days),A=(N,Y)=>N!=null&&Y!=null?Math.max(0,N-Y):null,x=(N,Y)=>N!=null&&Y?N/Y:null,P=[{name:"Medicare",pct:i.medicare_day_pct,adc:C(i.medicare_days),color:vt.Medicare,adm:i.medicare_admissions,disch:i.medicare_discharges,alos:i.medicare_alos,subs:[{name:"Traditional (FFS)",adc:C(A(i.medicare_days,i.ma_days))},{name:"Medicare Advantage",adc:C(i.ma_days)}]},{name:"Medicaid",pct:i.medicaid_day_pct,adc:C(i.medicaid_days),color:vt.Medicaid,adm:i.medicaid_admissions,disch:i.medicaid_discharges,alos:i.medicaid_alos,subs:[{name:"Traditional (FFS)",adc:C(A(i.medicaid_days,i.managed_medicaid_days))},{name:"Managed Medicaid",adc:C(i.managed_medicaid_days)}]},{name:"Other",pct:i.other_day_pct,adc:C(i.other_days),color:vt.Other,adm:i.other_admissions,disch:i.other_discharges,alos:x(i.other_days,i.other_discharges),subs:[]}].filter(N=>N.pct!=null&&N.pct>0).map(N=>({...N,subs:N.subs.filter(Y=>Y.adc!=null)})),$=x(i.total_days,i.total_discharges),T=P.some(N=>N.adm!=null||N.disch!=null)||i.total_discharges!=null||i.total_admissions!=null,F=y.filter(N=>N.facility_per_day!=null&&N.facility_per_day>0).sort((N,Y)=>Y.facility_per_day-N.facility_per_day).map(N=>({name:N.department,facility:N.facility_per_day,state:N.state_median_per_day})),R=i.operating_income,V=R>0?"text-emerald-600":R<0?"text-red-600":"text-slate-800",X=i.true_net_income>0?"text-emerald-600":i.true_net_income<0?"text-red-600":"text-slate-800",O=N=>v[N]?{rank:v[N].state_rank,total:v[N].n_facilities}:{},G=l.competitor_rank||{},J=G.peers||[],Z=new Set(["cost_per_day","nursing_cost_per_day","dietary_cost_per_day","therapy_cost_per_day","admin_cost_per_day","dso_days","labor_pct_of_costs","admin_pct_of_revenue","debt_to_equity"]),se=(N,Y,U)=>e.jsx(Ai,{peerRank:G[N],peers:J,metricKey:N,lowerBetter:Z.has(N),formatter:U,label:Y,currentCcn:t});return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex items-center gap-1.5 border-b border-slate-200",children:[["snapshot","Snapshot"],["trends","Multi-Year"],["worksheets","Worksheets"]].map(([N,Y])=>e.jsx("button",{onClick:()=>r(N),className:`px-3 py-1.5 text-sm font-medium border-b-2 -mb-px transition-colors ${n===N?"border-sky-600 text-sky-700":"border-transparent text-slate-500 hover:text-slate-700"}`,children:Y},N))}),n==="trends"?e.jsx(Li,{history:m,ccn:t,isCcrc:l.is_ccrc}):n==="worksheets"?e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm",children:e.jsx($i,{ccn:t,fyYear:s})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3",children:[p.length>1&&e.jsx("select",{value:s||i.fy_year,onChange:N=>a(Number(N.target.value)),className:"text-xs border border-slate-300 rounded-lg px-2 py-1 focus:outline-none focus:ring-2 focus:ring-sky-500",children:p.map(N=>e.jsxs("option",{value:N,children:["FY ",N,N===p[0]?" (latest)":""]},N))}),e.jsxs("p",{className:"text-[10px] text-slate-400",children:[p.length<=1?`FY${i.fy_year} · `:"","Rankings within ",l.state||"state"]}),e.jsxs(lt,{to:"/industry",className:"ml-auto inline-flex items-center gap-1 text-[11px] text-slate-500 hover:text-sky-600 transition-colors",title:"National industry financials (G then O)",children:["National financials",e.jsx(da,{size:11})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3",children:[e.jsx(We,{label:"Net Revenue",value:at(i.net_patient_revenue??i.net_revenue_after_medicare),sub:`Gross: ${at(i.gross_patient_revenue??i.total_revenue)}`,tip:"Wks G300000 Ln 3. Net Patient Revenue = Gross Patient Revenue (G-3 Ln 1) less Contractual Allowances and Discounts (G-3 Ln 2). Per CMS Form CMS-2540-10 spec. Falls back to net_revenue_after_medicare on legacy data.",...O("net_revenue_ppd")}),e.jsx(We,{label:"Op Income",value:st(R),color:V,sub:`${pe(i.operating_margin_pct)} margin`,tip:"Wks G300000 Ln 5. Net Patient Revenue minus Total Operating Expenses. Excludes non-operating items (donations, interest income, provider relief). Margin = (G-3 Ln 3 Net Patient Revenue â G-3 Ln 4 Total Op Exp) / G-3 Ln 3, per CMS Form 2540-10 spec.",...O("operating_margin_pct")}),e.jsx(We,{label:"Net Income",value:st(i.true_net_income),color:X,sub:`${pe(i.true_net_income_margin_pct)} margin`,tip:"Wks G300000 Ln 31. Final bottom line after all non-operating income (Ln 25: donations, interest, gains/losses, provider relief) and non-operating expense (Ln 30). Margin = G-3 Ln 31 / G-3 Ln 3 Net Patient Revenue.",badge:e.jsx(Fi,{lines:i.non_op_lines,nonOp:i.non_operating_income,totalRevenue:i.total_revenue}),...O("true_net_income_margin_pct")}),e.jsx(We,{label:"Current Ratio",value:i.current_ratio!=null?i.current_ratio.toFixed(2):"â",color:i.current_ratio==null?null:i.current_ratio>=1.5?"text-emerald-600":i.current_ratio<1?"text-red-600":"text-slate-800",sub:i.current_assets&&i.current_liabilities?`${st(i.current_assets)} / ${st(i.current_liabilities)}`:null,tip:"Liquidity ratio: Current Assets (G000000 Ln 11) / Current Liabilities (Ln 43). >1.5 = strong, <1.0 = stressed.",...O("current_ratio")}),e.jsx(We,{label:"Occupancy",value:pe(i.occupancy_pct),sub:`${i.beds||"--"} beds`,tip:"Calculated: Total Patient Days (S300001 Ln 1 Col 7) / Available Bed Days (S300001 Ln 1 Col 2) x 100.",...O("occupancy_pct")}),i.balance_sheet_suppressed?e.jsx(We,{label:"DSO",value:e.jsx("span",{className:"text-xs italic text-slate-400",title:"Data appears reported at a consolidated level",children:"Suppressed"}),tip:"Data appears reported at a consolidated level and may not reflect this facility."}):e.jsx(We,{label:"DSO",value:i.dso_days>=150?">150 days":`${vs(i.dso_days)} days`,sub:i.ar_gross!=null?`${st(i.ar_gross)} gross AR`:null,tip:"Calculated: (Net AR (Wks G000000 Ln 4) â Allowance for Uncollectible (Ln 6)) / (Net Patient Revenue (G-3 Ln 3) / 365). Lower = faster collections. Capped at 150 days. Net AR is the ending balance from the balance sheet.",...O("dso_days")})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[u.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700 mb-3 flex items-center gap-2",children:["Payer Mix & Census",e.jsx(le,{text:"Wks S300001 Ln 1. Medicare days (Col 4), Medicaid days (Col 5), Other days (Col 6), Total days (Col 7). ADC = payer days / days in the fiscal period. On the CMS-2540-24 form (FY2025+), Medicare splits into traditional (FFS) vs. Medicare Advantage and Medicaid into FFS vs. managed. ALOS = Col 14 (Medicare), Col 15 (Medicaid).",size:11,position:"below"})]}),e.jsxs("div",{className:"flex items-center gap-8",children:[e.jsx(je,{width:200,height:200,children:e.jsxs(di,{children:[e.jsx(ya,{data:u,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:54,outerRadius:92,paddingAngle:2,children:u.map(N=>e.jsx(Ft,{fill:vt[N.name]},N.name))}),e.jsx(ce,{formatter:N=>`${N.toFixed(1)}%`})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("table",{className:"w-full text-sm tabular-nums",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[9px] text-slate-400 uppercase tracking-wide",children:[e.jsx("th",{scope:"col",className:"text-left pb-2 font-semibold",children:"Payer"}),e.jsx("th",{scope:"col",className:"text-right pb-2 font-semibold",children:"ADC"}),T&&e.jsxs(e.Fragment,{children:[e.jsx("th",{scope:"col",className:"text-right pb-2 font-semibold",children:"Admits"}),e.jsx("th",{scope:"col",className:"text-right pb-2 font-semibold",children:"Dischg"}),e.jsx("th",{scope:"col",className:"text-right pb-2 font-semibold",title:"Average length of stay (days ÷ discharges)",children:"ALOS"})]}),e.jsx("th",{scope:"col",className:"text-right pb-2 font-semibold",children:"% days"})]})}),e.jsxs("tbody",{children:[P.map(N=>e.jsxs(b.Fragment,{children:[e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"py-1.5",children:e.jsxs("span",{className:"inline-flex items-center gap-2 font-medium text-slate-700",children:[e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:N.color}}),N.name]})}),e.jsx("td",{className:"py-1.5 text-right font-semibold text-slate-800",children:N.adc!=null?Math.round(N.adc).toLocaleStr
4ing():"â"}),T&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"py-1.5 text-right text-slate-600",children:N.adm!=null?N.adm.toLocaleString():"â"}),e.jsx("td",{className:"py-1.5 text-right text-slate-600",children:N.disch!=null?N.disch.toLocaleString():"â"}),e.jsx("td",{className:"py-1.5 text-right text-slate-600",children:N.alos!=null?Math.round(N.alos).toLocaleString():"â"})]}),e.jsxs("td",{className:"py-1.5 text-right text-slate-500",children:[N.pct.toFixed(1),"%"]})]}),N.subs.map(Y=>e.jsxs("tr",{className:"text-[12px] text-slate-500",children:[e.jsx("td",{className:"py-1 pl-5",children:Y.name}),e.jsx("td",{className:"py-1 text-right tabular-nums",children:Y.adc!=null?Math.round(Y.adc).toLocaleString():"â"}),T&&e.jsxs(e.Fragment,{children:[e.jsx("td",{}),e.jsx("td",{}),e.jsx("td",{})]}),e.jsx("td",{})]},Y.name))]},N.name)),e.jsxs("tr",{className:"border-t border-slate-200 font-semibold",children:[e.jsx("td",{className:"py-1.5 text-slate-700",children:"Total"}),e.jsx("td",{className:"py-1.5 text-right text-slate-800",children:g!=null?Math.round(g).toLocaleString():"â"}),T&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"py-1.5 text-right text-slate-700",children:i.total_admissions!=null?i.total_admissions.toLocaleString():"â"}),e.jsx("td",{className:"py-1.5 text-right text-slate-700",children:i.total_discharges!=null?i.total_discharges.toLocaleString():"â"}),e.jsx("td",{className:"py-1.5 text-right text-slate-700",children:$!=null?Math.round($).toLocaleString():"â"})]}),e.jsx("td",{className:"py-1.5 text-right text-slate-500",children:"100%"})]})]})]}),e.jsxs("div",{className:"pt-3 mt-2 border-t border-slate-100 space-y-1 text-xs text-slate-500",children:[e.jsx("p",{children:"ADC = patient days ÷ days in period. ALOS = covered days ÷ discharges (Medicare/Medicaid as reported on S-3; Other/Total computed)."}),(i.ma_days!=null||i.managed_medicaid_days!=null)&&e.jsx("p",{className:"text-[11px] text-indigo-600/80 pt-0.5",children:"Medicare Advantage / managed Medicaid split newly reported on the CMS-2540-24 form."})]})]})]})]}),h.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700 mb-2 flex items-center gap-2",children:["vs. ",l.state," Benchmarks",e.jsx(le,{text:`Compared to ${v.operating_margin_pct?.n_facilities||"--"} facilities in ${l.state} for FY${i.fy_year}.`,size:11,position:"below"})]}),e.jsxs("div",{className:"flex items-center gap-2 py-1 text-[9px] text-slate-500 uppercase tracking-wide",children:[e.jsx("span",{className:"w-36 text-right",children:"Metric"}),e.jsx("span",{className:"w-16 text-right",children:"Facility"}),e.jsx("span",{className:"w-12 text-right",children:"P25"}),e.jsx("span",{className:"w-12 text-right",children:"Median"}),e.jsx("span",{className:"w-12 text-right",children:"P75"}),e.jsx("span",{className:"w-16 text-right",children:"State Rank"}),e.jsx("span",{className:"w-24 text-right",children:"Peers (â¤11)"})]}),[["true_net_income_margin_pct",!0,pe],["occupancy_pct",!0,pe],["current_ratio",!0,N=>N!=null?N.toFixed(2):"â"],["net_revenue_ppd",!0,we],["cost_per_day",!1,we],["nursing_cost_per_day",!1,we],["dso_days",!1,vs],["medicare_day_pct",null,pe],["medicaid_day_pct",null,pe],["admin_pct_of_revenue",!1,pe]].map(([N,Y,U])=>{const H=v[N];return H?e.jsx(Pi,{label:H.label,facility:H.facility_value,p25:H.state_p25,median:H.state_median,p75:H.state_p75,rank:H.state_rank,total:H.n_facilities,higherBetter:Y,format:U,peerRankBadge:se(N,H.label,U)},N):null})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[F.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700 mb-1 flex items-center gap-2",children:["Cost Per Patient Day by Department",e.jsx(le,{text:"Wks A000000 Col 7 (net cost after adjustments) for each department line, divided by Total Patient Days (S300001 Ln 1 Col 7). Nursing = Ln 30, Admin = Ln 4, Benefits = Ln 3, Capital (Depr/Rent/Lease) = Ln 1+2, Dietary = Ln 8, Therapy = Ln 44+45+46, Plant Ops = Ln 5, Housekeeping = Ln 7, Drugs = Ln 49, Social Svc = Ln 13, Laundry = Ln 6, Nursing Admin = Ln 9.",size:11,position:"below"})]}),e.jsxs("div",{className:"flex items-center gap-3 mb-3 text-[10px] text-slate-400",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded bg-slate-500"})," This Facility"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded bg-slate-200"})," ",l.state," Median"]})]}),e.jsx(je,{width:"100%",height:F.length*40+30,children:e.jsxs(it,{data:F,layout:"vertical",margin:{top:4,right:40,bottom:4,left:4},children:[e.jsx(de,{type:"number",tickFormatter:N=>`$${N}`,tick:{fontSize:11}}),e.jsx(xe,{type:"category",dataKey:"name",width:145,tick:{fontSize:11}}),e.jsx(ce,{content:({active:N,payload:Y})=>
4{if(!N||!Y?.length)return null;const U=Y[0]?.payload,H=U.facility&&U.state?U.facility-U.state:null;return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg shadow-lg p-2.5 text-xs",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:U.name}),e.jsxs("p",{className:"text-slate-700",children:["Facility: $",U.facility?.toFixed(2),"/day"]}),U.state&&e.jsxs("p",{className:"text-slate-400",children:["State median: $",U.state.toFixed(2),"/day"]}),H!=null&&e.jsxs("p",{className:H>0?"text-red-500":"text-emerald-500",children:[H>0?"+":"",H.toFixed(2),"/day vs state"]})]})}}),e.jsx(_e,{dataKey:"facility",fill:"#64748b",radius:[0,3,3,0],barSize:14}),e.jsx(_e,{dataKey:"state",fill:"#e2e8f0",radius:[0,3,3,0],barSize:14})]})}),e.jsxs("p",{className:"text-[10px] text-slate-500 mt-2 text-right",children:["Total: ",we(i.cost_per_day),"/day (facility) vs ",we(v.cost_per_day?.state_median),"/day (state median)"]})]}),(i.nursing_labor||D.length>0)&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700 mb-3 flex items-center gap-2",children:[i.nursing_labor?"Staffing Costs & Agency Reliance":"Staffing Costs & Hourly Rates by Role",e.jsx(le,{text:"Nursing (Wks S-3 Part V): employee vs. agency rates incl. allocated fringe; premium = agency vs. employee rate. Other departments (Part III): salary only, no benefits. State median = same state & fiscal year.",size:11,position:"below"})]}),i.nursing_labor&&e.jsx(Ri,{nl:i.nursing_labor}),B.length>0&&e.jsx("div",{className:`overflow-x-auto ${i.nursing_labor?"mt-4":""}`,children:e.jsxs("table",{className:"w-full text-xs tabular-nums",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-100 text-[9px] text-slate-400 uppercase tracking-wide",children:[e.jsx("th",{scope:"col",className:"text-left py-1.5 pr-2 font-semibold",children:"Role"}),e.jsx("th",{scope:"col",className:"text-right py-1.5 px-1 font-semibold",children:z?"Employee":"Rate"}),z&&e.jsxs(e.Fragment,{children:[e.jsx("th",{scope:"col",className:"text-right py-1.5 px-1 font-semibold",children:"Agency"}),e.jsx("th",{scope:"col",className:"text-right py-1.5 px-1 font-semibold",children:"Premium"})]}),e.jsx("th",{scope:"col",className:"text-right py-1.5 px-1 font-semibold",children:"Contract %"}),e.jsx("th",{scope:"col",className:"text-right py-1.5 px-1 font-semibold",title:`${l.state} median rate`,children:l.state}),e.jsx("th",{scope:"col",className:"text-right py-1.5 pl-1 font-semibold",children:"Rank"})]})}),e.jsx("tbody",{children:B.map((N,Y)=>{const U=N.section&&(Y===0||B[Y-1].section!==N.section),H=N.contractPct,ae=N.emp==null&&(H||0)>=100;return e.jsxs(b.Fragment,{children:[U&&e.jsx("tr",{children:e.jsx("td",{colSpan:_,className:"pt-3 pb-1 text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:N.section})}),e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"py-1.5 pr-2 font-medium text-slate-700 whitespace-nowrap",children:N.role}),ae?e.jsx("td",{colSpan:_-1,className:"py-1.5 px-1 text-left text-[10px] text-slate-400 italic",children:"100% contracted"}):e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"py-1.5 px-1 text-right font-semibold text-slate-800",children:N.emp!=null?`$${N.emp.toFixed(2)}`:"â"}),z&&e.jsxs(e.Fragment,{children:[e.jsx("td",{className:"py-1.5 px-1 text-right text-slate-600",children:N.agency!=null?`$${N.agency.toFixed(2)}`:"â"}),e.jsx("td",{className:"py-1.5 px-1 text-right text-slate-600 font-medium",children:N.premium!=null?`+${Math.round(N.premium)}%`:"â"})]}),e.jsx("td",{className:`py-1.5 px-1 text-right ${H>30?"text-amber-600 font-medium":"text-slate-500"}`,children:H!=null?`${Math.round(H)}%`:"â"}),e.jsx("td",{className:"py-1.5 px-1 text-right text-slate-400",children:N.median!=null?`$${N.median.toFixed(2)}`:"â"}),e.jsx("td",{className:"py-1.5 pl-1 text-right text-[10px] text-sky-600 font-medium",children:N.rank&&N.total?`#${N.rank}/${N.total}`:""})]})]})]},N.key)})})]})})]})]})]})]})}const Tt=7,ws=[["adc","Avg Daily Census"],["occupancy_pct","Occupancy"],["revenue_per_day","Revenue / Day"],["operating_margin_pct","Op. Margin"]];function Ti(t){if(t.length===1)return t[0];const s=p=>p.fy_start&&p.fy_end?Math.round((new Date(p.fy_end)-new Date(p.fy_start))/864e5)+1:365;if(t.reduce((p,i)=>p+s(i),0)>400)return[...t].sort((p,i)=>p.fy_end<i.fy_end?-1:1)[t.length-1];const a=p=>t.some(i=>i[p]!=null)?t.reduce((i,h)=>i+(Number(h[p])||0),0):null,n=p=>{let i=0,h=0;for(const v of t)v[p]!=null&&v.total_days&&(i+=Number(v[p])*v.total_days,h+=v.total_days);return h?i/h:null},r=[...t].sort((p,i)=>p.fy_end<i.fy_end?-1:1),l=r[r.length-1],o=a("total_days"),d=a("total_revenue"),c=a("net_patient_revenue"),m=a("operating_income");return{...l,fy_start:r[0].fy_start,fy_end:l.fy_end,total_days:o,total_revenue:d,net_patient_revenue:c,operating_income:m,net_income:a("net_income"),true_net_income:a("true_net_income"),revenue_per_day:d!=null&&o?d/o:null,operating_margin_pct:m!=null&&c?m/c*100:null,occupancy_pct:n("occupancy_pct"),cost_per_day:n("cost_per_day"),nursing_cost_per_day:n("nursing_cost_per_day"),therapy_cost_per_day:n("therapy_cost_per_day"),dietary_cost_per_day:n("dietary_cost_per_day"),admin_cost_per_day:n("admin_cost_per_day"),benefits_cost_per_day:n("benef
4its_cost_per_day"),medicare_day_pct:n("medicare_day_pct"),medicaid_day_pct:n("medicaid_day_pct"),other_day_pct:n("other_day_pct")}}function Li({history:t,ccn:s,isCcrc:a=!1}){const[n,r]=b.useState("recent"),[l,o]=b.useState("adc"),[d,c]=b.useState(!1),[m,p]=b.useState(!1),i=De(()=>p(!1),{enabled:m}),h=new Map;for(const x of t)h.has(x.fy_year)||h.set(x.fy_year,[]),h.get(x.fy_year).push(x);const v=[...h.values()].map(Ti).sort((x,P)=>x.fy_year-P.fy_year);if(!v.length)return e.jsx("p",{className:"text-sm text-slate-400 py-12 text-center",children:"No cost report history for this facility yet."});const y=v[0].fy_year,L=v.some(x=>x.fy_year<2011),D=v.some(x=>x.fy_year>=2011),j=v.length>Tt,M=[["recent",`Last ${Tt}`]];L&&D&&M.push(["modern","Since 2011"]),M.push(["all",L?`Since ${y}`:"All years"]);const f=n==="modern"?v.filter(x=>x.fy_year>=2011):n==="all"?v:v.slice(-Tt),w=(ws.find(x=>x[0]===l)||[])[1]||"",B=l==="revenue_per_day"?x=>`$${Math.round(x)}`:l==="adc"?x=>Math.round(x).toLocaleString():x=>`${Math.round(x)}%`,z=x=>{if(x.total_days==null)return null;let P=365;if(x.fy_start&&x.fy_end){const $=Math.round((new Date(x.fy_end)-new Date(x.fy_start))/864e5)+1;$>0&&$<800&&(P=$)}return x.total_days/P},_=x=>x!=null?x.toFixed(2):"--",S=x=>x!=null?Math.round(x).toLocaleString():"--",u=[["Census & Occupancy",[["Certified Beds",x=>x.beds,Ns],["Total Patient Days",x=>x.total_days,Ns],["Avg Daily Census",x=>z(x),S],["Occupancy %",x=>x.occupancy_pct,pe]]],["Revenue",[["Net Patient Revenue",x=>x.net_patient_revenue,at],["Revenue / Day",x=>x.revenue_per_day,we],["Gross Patient Revenue",x=>x.total_revenue,at]]],["Profitability",[["Operating Income",x=>x.operating_income,at],["Net Income",x=>x.true_net_income??x.net_income,at],["Operating Margin %",x=>x.operating_margin_pct,pe]]],["Cost / Resident Day",[["Total Cost / Day",x=>x.cost_per_day,we],["Nursing / Day",x=>x.nursing_cost_per_day,we],["Therapy / Day",x=>x.therapy_cost_per_day,we],["Dietary / Day",x=>x.dietary_cost_per_day,we],["Admin / Day",x=>x.admin_cost_per_day,we],["Benefits / Day",x=>x.benefits_cost_per_day,we]]],["Payer Mix (patient days)",[["Medicare %",x=>x.medicare_day_pct,pe],["Medicaid %",x=>x.medicaid_day_pct,pe],["Other %",x=>x.other_day_pct,pe]]],["Liquidity",[["Days Cash on Hand",x=>x.days_cash_on_hand,S],["Current Ratio",x=>x.current_ratio,_]]]].map(([x,P])=>[x,P.filter(([,$])=>f.some(T=>$(T)!=null))]).filter(([,x])=>x.length>0),g=()=>{const x=u.flatMap(([$,T])=>T.map(([F,R])=>{const V={Section:$,Metric:F};for(const X of f)V[`FY${X.fy_year}`]=R(X)??"";return V})),P=["Section","Metric",...f.map($=>`FY${$.fy_year}`)];Gt(x,P,`financial-trends-${s||"facility"}.csv`)},A=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-4 py-2.5 border-b border-slate-100 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-slate-700",children:["Financial Trends â ",n==="all"?"full history":n==="modern"?"since 2011":`last ${f.length} fiscal ${f.length===1?"year":"years"}`]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"CMS cost reports. A blank cell means the value was not reported that year."})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-shrink-0",children:[j&&e.jsx("div",{className:"flex items-center rounded-md border border-slate-200 overflow-hidden",children:M.map(([x,P])=>e.jsx("button",{onClick:()=>r(x),className:`text-xs px-2.5 py-1 font-medium transition-colors ${n===x?"bg-slate-800 text-white":"text-slate-500 hover:text-sky-600"}`,children:P},x))}),e.jsxs("button",{onClick:g,className:"flex items-center gap-1 text-xs text-slate-500 hover:text-sky-600 font-medium transition-colors",children:[e.jsx(Ue,{size:13})," CSV"]}),!m&&e.jsxs("button",{onClick:()=>p(!0),title:"Open full screen",className:"flex items-center gap-1 text-xs text-slate-500 hover:text-sky-600 font-medium transition-colors",children:[e.jsx(ft,{size:13})," Expand"]})]})]}),v.length>=3&&e.jsxs("div",{className:"border-b border-slate-100",children:[e.jsxs("button",{onClick:()=>c(x=>!x),className:"w-full px-4 py-2 flex items-center justify-between text-xs font-medium text-slate-500 hover:text-sky-600 transition-colors",children:[e.jsxs("span",{children:["Trend chart ",e.jsxs("span",{className:"font-normal text-slate-400 tabular-nums",children:["· ",v[0].fy_year,"â",v[v.length-1].fy_year]})]}),e.jsx(ye,{size:14,className:`transition-transform ${d?"rotate-180":""}`})]}),d&&e.jsxs("div",{className:"px-4 pb-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5 flex-wrap",children:ws.map(([x,P])=>e.jsx("button",{onClick:()=>o(x),className:`text-[11px] px-2 py-0.5 rounded font-medium transition-colors ${l===x?"bg-sky-50 text-sky-700":"text-slate-400 hover:text-slate-600"}`,children:P},x))}),e.jsx(je,{width:"100%",height:180,children:e.jsxs($e,{data:v.map(x=>({...x,adc:z(x)})),margin:{top:5,right:10,left:0,bottom:0},children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9",vertical:!1}),e.jsx(de,{dataKey:"fy_year",tick:{fontSize:10,fill:"#94a3b8"},interval:"preserveStartEnd",minTickGap:22}),e.jsx(xe,{tick:{fontSize:10,fill:"#94a3b8"}
4,width:46,tickFormatter:B,domain:[x=>Math.floor(x-Math.max(1,Math.abs(x)*.06)),x=>Math.ceil(x+Math.max(1,Math.abs(x)*.06))]}),e.jsx(ce,{formatter:x=>[B(x),w],labelFormatter:x=>`FY${x}`,contentStyle:{fontSize:12,borderRadius:8,border:"1px solid #e2e8f0"}}),L&&D&&e.jsx(ss,{x:2011,stroke:"#cbd5e1",strokeDasharray:"4 4",label:{value:"form change",position:"insideTopRight",fontSize:9,fill:"#94a3b8"}}),e.jsx(oe,{type:"monotone",dataKey:l,stroke:"#0284c7",strokeWidth:2,dot:{r:1.5},connectNulls:!0,isAnimationActive:!1})]})})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"min-w-full text-xs tabular-nums",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left font-semibold text-slate-500 px-3 py-2 sticky left-0 bg-slate-50 min-w-[150px]",children:"Metric"}),f.map(x=>{const P=x.fy_year<2011;return e.jsxs("th",{scope:"col",title:P?"Earlier CMS form (2540-96) â core metrics only":void 0,className:`text-right font-semibold px-3 py-2 whitespace-nowrap ${P?"text-slate-400":"text-slate-700"}`,children:["FY",x.fy_year,P?"*":""]},x.fy_year)})]})}),e.jsx("tbody",{children:u.map(([x,P])=>e.jsxs(b.Fragment,{children:[e.jsx("tr",{children:e.jsx("td",{colSpan:f.length+1,className:"px-3 pt-3 pb-1 text-[10px] font-semibold uppercase tracking-wide text-sky-700",children:x})}),P.map(([$,T,F])=>e.jsxs("tr",{className:"border-t border-slate-100 hover:bg-slate-50",children:[e.jsx("td",{className:"px-3 py-1.5 text-slate-600 sticky left-0 bg-white",children:$}),f.map(R=>{const V=T(R);return e.jsx("td",{className:"px-3 py-1.5 text-right font-mono text-slate-800",children:V!=null?F(V):e.jsx("span",{className:"text-slate-300",children:"â"})},R.fy_year)})]},$))]},x))})]})}),f.some(x=>x.fy_year<2011)&&e.jsx("p",{className:"px-4 py-2 text-[10px] text-slate-400 border-t border-slate-100",children:"* Years before 2011 use the earlier CMS cost-report form (2540-96) â core operating metrics only. Cost-per-day and liquidity detail begin in 2011."})]});return m?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-3",onClick:()=>p(!1),children:e.jsxs("div",{ref:i,role:"dialog","aria-modal":"true","aria-labelledby":"trends-expanded-title",className:"flex max-h-[96vh] min-w-[36rem] max-w-[98vw] flex-col overflow-hidden rounded-xl bg-white shadow-xl",onClick:x=>x.stopPropagation(),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-slate-200 px-4 py-3",children:[e.jsxs("div",{id:"trends-expanded-title",className:"text-sm font-semibold text-slate-800",children:["Financial Trends · CCN ",s]}),e.jsx(ts,{onClick:()=>p(!1),label:"Close full screen"})]}),e.jsx("div",{className:"flex min-h-0 flex-1 flex-col overflow-auto",children:A})]})}):e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:A})}function ks(t){if(!t)return[0,1/0];const s=t.trim();if(s.startsWith(">"))return[parseFloat(s.slice(1))+.001,1/0];const[a,n]=s.split("-").map(parseFloat);return[isNaN(a)?0:a,isNaN(n)?1/0:n]}function Ss(t,s){const a=Qt[t];if(!a||s==null)return null;for(const n of[5,4,3,2,1]){const[r,l]=ks(a[String(n)]);if(s>=r&&s<=l){let o=null;if(n<5){const[,c]=ks(a[String(n+1)]);o=Math.max(0,s-c)}let d=null;return n>1&&l!==1/0&&(d=l-s),{stars:n,range:[r,l],to_next_higher:o,to_next_lower:d}}}return null}const Qt={AK:{5:"0.000-14.000",4:"14.001-35.000",3:"35.001-75.000",2:"75.001-121.500",1:">121.500"},AL:{5:"0.000-3.000",4:"3.001-11.000",3:"11.001-23.000",2:"23.001-46.000",1:">46.000"},AR:{5:"0.000-10.000",4:"10.001-20.000",3:"20.001-32.000",2:"32.001-50.000",1:">50.000"},AZ:{5:"0.000-11.000",4:"11.001-24.000",3:"24.001-38.000",2:"38.001-55.000",1:">55.000"},CA:{5:"0.000-32.000",4:"32.001-66.000",3:"66.001-97.000",2:"97.001-149.000",1:">149.000"},CO:{5:"0.000-22.000",4:"22.001-45.000",3:"45.001-73.000",2:"73.001-107.000",1:">107.000"},CT:{5:"0.000-30.000",4:"30.001-51.000",3:"51.001-76.250",2:"76.251-112.750",1:">112.750"},DC:{5:"0.000-21.000",4:"21.001-91.500",3:"91.501-206.750",2:"206.751-440.000",1:">440.000"},DE:{5:"0.000-20.000",4:"20.001-54.000",3:"54.001-79.500",2:"79.501-130.250",1:">130.250"},FL:{5:"0.000-8.000",4:"8.001-26.000",3:"26.001-46.000",2:"46.001-87.000",1:">87.000"},GA:{5:"0.000-10.000",4:"10.001-25.000",3:"25.001-42.000",2:"42.001-70.000",1:">70.000"},GU:{5:"0.000-13.000",4:"13.001-36.000",3:"36.001-65.000",2:"65.001-118.500",1:">118.500"},HI:{5:"0.000-27.000",4:"27.001-48.000",3:"48.001-71.000",2:"71.001-97.000",1:">97.000"},IA:{5:"0.000-6.000",4:"6.001-21.000",3:"21.001-40.750",2:"40.751-84.000",1:">84.000"}
4,ID:{5:"0.000-26.000",4:"26.001-45.000",3:"45.001-62.000",2:"62.001-85.000",1:">85.000"},IL:{5:"0.000-31.000",4:"31.001-74.000",3:"74.001-120.000",2:"120.001-218.000",1:">218.000"},IN:{5:"0.000-9.000",4:"9.001-24.000",3:"24.001-42.000",2:"42.001-72.000",1:">72.000"},KS:{5:"0.000-27.000",4:"27.001-49.000",3:"49.001-73.000",2:"73.001-121.625",1:">121.625"},KY:{5:"0.000-2.000",4:"2.001-12.000",3:"12.001-22.000",2:"22.001-47.000",1:">47.000"},LA:{5:"0.000-17.000",4:"17.001-36.000",3:"36.001-55.000",2:"55.001-90.375",1:">90.375"},MA:{5:"0.000-6.500",4:"6.501-27.000",3:"27.001-44.000",2:"44.001-81.000",1:">81.000"},MD:{5:"0.000-32.000",4:"32.001-75.000",3:"75.001-108.000",2:"108.001-167.375",1:">167.375"},ME:{5:"0.000-24.000",4:"24.001-55.000",3:"55.001-82.000",2:"82.001-115.500",1:">115.500"},MI:{5:"0.000-17.000",4:"17.001-47.000",3:"47.001-78.000",2:"78.001-131.750",1:">131.750"},MN:{5:"0.000-9.000",4:"9.001-29.000",3:"29.001-55.500",2:"55.501-94.500",1:">94.500"},MO:{5:"0.000-21.000",4:"21.001-53.000",3:"53.001-93.750",2:"93.751-162.000",1:">162.000"},MS:{5:"0.000-14.000",4:"14.001-28.000",3:"28.001-44.000",2:"44.001-82.000",1:">82.000"},MT:{5:"0.000-31.500",4:"31.501-55.000",3:"55.001-91.000",2:"91.001-131.625",1:">131.625"},NC:{5:"0.000-4.000",4:"4.001-16.000",3:"16.001-37.000",2:"37.001-78.250",1:">78.250"},ND:{5:"0.000-9.000",4:"9.001-23.000",3:"23.001-38.000",2:"38.001-78.500",1:">78.500"},NE:{5:"0.000-11.000",4:"11.001-30.000",3:"30.001-48.000",2:"48.001-90.000",1:">90.000"},NH:{5:"0.000-7.000",4:"7.001-14.000",3:"14.001-22.000",2:"22.001-34.000",1:">34.000"},NJ:{5:"0.000-19.000",4:"19.001-37.000",3:"37.001-62.000",2:"62.001-94.000",1:">94.000"},NM:{5:"0.000-61.000",4:"61.001-100.000",3:"100.001-157.500",2:"157.501-217.000",1:">217.000"},NV:{5:"0.000-17.000",4:"17.001-28.000",3:"28.001-49.000",2:"49.001-76.000",1:">76.000"},NY:{5:"0.000-11.000",4:"11.001-26.000",3:"26.001-44.000",2:"44.001-77.000",1:">77.000"},OH:{5:"0.000-16.000",4:"16.001-41.000",3:"41.001-69.000",2:"69.001-121.250",1:">121.250"},OK:{5:"0.000-13.000",4:"13.001-36.000",3:"36.001-55.750",2:"55.751-96.000",1:">96.000"},OR:{5:"0.000-16.000",4:"16.001-44.000",3:"44.001-67.500",2:"67.501-99.000",1:">99.000"},PA:{5:"0.000-8.000",4:"8.001-32.000",3:"32.001-67.000",2:"67.001-126.500",1:">126.500"},PR:{5:"0.000-34.000",4:"34.001-52.000",3:"52.001-208.000",2:"208.001-284.000",1:">284.000"},RI:{5:"0.000-30.000",4:"30.001-57.500",3:"57.501-102.250",2:"102.251-169.500",1:">169.500"},SC:{5:"0.000-3.000",4:"3.001-17.000",3:"17.001-34.000",2:"34.001-61.500",1:">61.500"},SD:{5:"0.000-14.000",4:"14.001-35.000",3:"35.001-60.000",2:"60.001-106.000",1:">106.000"},TN:{5:"0.000-9.000",4:"9.001-18.000",3:"18.001-33.000",2:"33.001-65.750",1:">65.750"},TX:{5:"0.000-26.000",4:"26.001-52.000",3:"52.001-87.750",2:"87.751-160.000",1:">160.000"},UT:{5:"0.000-15.000",4:"15.001-39.000",3:"39.001-63.000",2:"63.001-121.000",1:">121.000"},VA:{5:"0.000-16.000",4:"16.001-44.000",3:"44.001-78.000",2:"78.001-163.500",1:">163.500"},VT:{5:"0.000-27.000",4:"27.001-51.000",3:"51.001-81.000",2:"81.001-149.250",1:">149.250"},WA:{5:"0.000-37.000",4:"37.001-72.000",3:"72.001-101.000",2:"101.001-177.000",1:">177.000"},WI:{5:"0.000-12.000",4:"12.001-39.000",3:"39.001-77.750",2:"77.751-131.250",1:">131.250"},WV:{5:"0.000-29.000",4:"29.001-61.000",3:"61.001-100.000",2:"100.001-175.000",1:">175.000"},WY:{5:"0.000-14.000",4:"14.001-32.000",3:"32.001-69.000",2:"69.001-100.000",1:">100.000"}};function Te({text:t="Loading..."}){return e.jsxs("div",{className:"flex items-center gap-2 text-slate-400 py-12 justify-center",children:[e.jsx(ge,{size:18,className:"animate-spin"})," ",t]})}function _a({msg:t}){return e.jsx("div",{className:"p-3 md:p-6",children:e.jsx("div",{className:"bg-red-50 border border-red-200 text-red-700 rounded-lg p-4 text-sm",children:t})})}function bt({text:t}){return e.jsx("div",{className:"bg-amber-50 border border-amber-200 text-amber-800 rounded-lg p-4 text-sm",children:t})}function Oi({title:t,sub:s,children:a,rightHeader:n}){const[r,l]=b.useState(!1),o=e.jsxs("div",{className:`bg-white rounded-xl border border-slate-200 shadow-sm p-5 ${r?"fixed inset-4 z-50 overflow-auto":""}`,children:[e.jsxs("div",{className:"flex items-start justify-between mb-0.5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700",children:t}),s&&e.jsx("p",{className:"text-xs text-slate-400 mb-3",children:s})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[n,e.jsx("button",{onClick:()=>l(d=>!d),className:"text-slate-400 hover:text-slate-700 transition-colors",title:r?"Exit fullscreen":"Fullscreen",children:r?e.jsx(xa,{size:14}):e.jsx(ft,{size:14})})]})]}),e.jsx("div",{className:"mt-3",children:typeof a=="function"?a(r):a})]});return r?e.jsxs(e.Fragment,{children:[o,e.jsx("div",{className:"fixed inset-0 bg-black/30 z-40",onClick:()=>l(!1)})]}):o}function Ei({children:t,right:s}){return e.jsx("th",{className:`px-3 py-2 text-xs font-semibold text-slate-500 uppercase tracking-wide ${s?"text-right":"text-left"}`,children:t})}function ne({children:t,mono:s,small:a,right:n,bold:r,grey:l}){return e.jsx("td",{className:`px-3 py-2 ${s?"font-mono":""} ${a?"text-xs":""} ${n?"text-right":""} ${r?"font-medium":""} ${l?"text-slate-400":"text-slate-600"}`,children:t})}const Ct={A:"Isolated · No actual harm, potential for minimal harm",B:"Pattern · No actual harm, potential for minimal harm",C:"Widespread · No actual harm, potential for minimal harm",D:"Isolated · No actual harm, potential for more than minimal harm",E:"Pattern · No actual harm, potential for more than minimal harm",F:"Widespread · No actual harm, potential for more than minimal harm",G:"Isolated · Actual harm, not immediate jeopardy",H:"Pattern · Actual harm, not immediate jeopardy",I:"Widespread · Actual harm, not immediate jeopardy",J:"Isolated · Immediate jeopardy",K:"Pattern · Immediate jeopardy",L:"Widespread · Immediate jeopardy"},Ii={A:0,B:0,C:0,D:4,E:8,F:16,G:20,H:35,I:45,J:50,K:100,L:150},Xe=t=>Ii[t]||0,Lt=[{key:"cognitive",label:"Cognitive",short:"Cognitive",prefix:"C",desc:"Mental status, orientation, delirium"},{key:"mood",label:"Mood & Depression",short:"Mood",prefix:"D",desc:"PHQ-9, social isolation"},{key:"behavior",label:"Behavior",short:"Behavior",prefix:"E",desc:"Psychosis, wandering"},{key:"functional",label:"Functional Abilities",short:"Function",prefix:"GG",desc:"Self-care, mobility, ADLs"},{key:"continence",label:"Bladder & Bowel",short:"Continence",prefix:"H",desc:"Continence, toileting programs"},{key:"diagnoses",label:"Active Diagnoses",short:"Diagnoses",prefix:"I",desc:"Medical conditions"},{key:"health",label:"Health Conditions",short:"Health",prefix:"J",desc:"Pain, falls, surgeries"},{key:"nutrition",label:"Nutrition & Swallowing",short:"Nutrition",prefix:"K",desc:"Weight loss, diet"},{key:"skin",label:"Skin Conditions",short:"Skin",prefix:"M",desc:"Pressure ulcers, wounds"},{key:"medications",label:"Medications",short:"Meds",prefix:"N",desc:"Antipsychotics, opioids, high-risk drugs"},{key:"treatments",label:"Special Treatments",short:"Treatments",prefix:"O",desc:"IV, ventilator, dialysis, oxygen"},{key:"other",label:"Other",short:"Other",prefix:null,desc:"Demographics, discharge, participation"}];function zi(t,s){return s.prefix?s.prefix==="GG"?t.startsWith("GG"):t.startsWith(s.prefix)&&!t.startsWith("GG"):!0}const Pe={5:"#059669",4:"#0284c7",3:"#d97706",2:"#f97316",1:"#dc2626"};function Bi({ccn:t,facility:s,initialSubTab:a}){const n=["scorecard","nta","outcomes","clinical"],[r,l]=b.useState(a&&n.includes(a)?a:"scorecard");return e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"flex gap-1 border-b border-slate-200 overflow-x-auto scrollbar-hide",children:[{key:"scorecard",label:"QM Star Scorecard"},{key:"nta",label:"Clinical Acuity"},{key:"outcomes",label:"Quality Outcomes"},{key:"clinical",label:"MDS Clinical Detail"}].map(o=>e.jsx("button",{onClick:()=>l(o.key),className:`px-4 py-2 text-sm font-medium whitespace-nowrap border-b-2 transition-colors ${r===o.key?"border-sky-600 text-sky-700":"border-transparent text-slate-500 hover:text-slate-700"}`,children:o.label},o.key))}),r==="scorecard"&&e.jsx(Ki,{ccn:t,facility:s}),r==="nta"&&e.jsx(Qi,{ccn:t}),r==="outcomes"&&e.jsx(Gi,{ccn:t,facility:s}),r==="clinical"&&e.jsx(Ui,{ccn:t,facility:s})]})}function Ot({label:t,total:s,max:a,thresholds:n,onClose:r}){const l=Math.min(...n.map(c=>c[0])),o=c=>Math.round((c-l)/a*100),d=De(r);return e.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-black/40",onClick:r,children:e.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-labelledby":"star-threshold-title",className:"bg-white rounded-lg shadow-lg p-4 md:p-6 w-full max-w-[520px]",onClick:c=>c.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsxs("h3",{id:"star-threshold-title",className:"text-base font-bold text-slate-800",children:[t," â Star Thresholds"]}),s!=null&&e.jsxs("p",{className:"text-sm text-slate-500 mt-0.5",children:["Total Points: ",e.jsx("span",{className:"font-bold text-slate-800",children:s.toLocaleStr
4ing()})," / ",a.toLocaleString()]})]}),e.jsx("button",{onClick:r,"aria-label":"Close",className:"text-slate-400 hover:text-slate-600",children:e.jsx(Me,{size:18})})]}),e.jsxs("div",{className:"relative h-10 rounded-lg overflow-hidden flex mb-2",children:[[1,2,3,4,5].map(c=>{const m=n.find(i=>i[2]===c);if(!m)return null;const p=(m[1]-m[0]+1)/a*100;return e.jsx("div",{className:"relative h-full flex items-center justify-center",style:{width:`${p}%`,backgroundColor:Pe[c]+"22",borderRight:"1px solid white"},children:e.jsxs("span",{className:"text-xs font-bold",style:{color:Pe[c]},children:[c,"â
"]})},c)}),s!=null&&e.jsxs("div",{className:"absolute top-0 bottom-0",style:{left:`${o(s)}%`},children:[e.jsx("div",{className:"absolute -translate-x-1/2 w-0.5 h-full bg-slate-900"}),e.jsx("div",{className:"absolute -translate-x-1/2 -top-5 bg-slate-900 text-white text-[10px] font-bold px-1.5 py-0.5 rounded whitespace-nowrap",children:s})]})]}),e.jsxs("table",{className:"w-full text-xs mt-4",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-slate-200",children:[e.jsx("th",{scope:"col",className:"text-left py-1 text-slate-500",children:"Star"}),e.jsx("th",{scope:"col",className:"text-right py-1 text-slate-500",children:"Min Points"}),e.jsx("th",{scope:"col",className:"text-right py-1 text-slate-500",children:"Max Points"}),e.jsx("th",{scope:"col",className:"text-right py-1 text-slate-500",children:"Gap"})]})}),e.jsx("tbody",{children:[5,4,3,2,1].map(c=>{const m=n.find(i=>i[2]===c);if(!m)return null;const p=s!=null&&s>=m[0]&&s<=m[1];return e.jsxs("tr",{className:p?"bg-sky-50 font-semibold":"",children:[e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block w-5 h-5 rounded-full text-center text-white text-[10px] font-bold leading-5",style:{backgroundColor:Pe[c]},children:c})}),e.jsx("td",{className:"text-right py-1.5",children:m[0].toLocaleString()}),e.jsx("td",{className:"text-right py-1.5",children:m[1].toLocaleString()}),e.jsx("td",{className:"text-right py-1.5 text-slate-500",children:s!=null?s>=m[0]&&s<=m[1]?e.jsx("span",{className:"text-sky-600 font-medium",children:"Current"}):s<m[0]?e.jsxs("span",{className:"text-slate-400",children:[(m[0]-s).toLocaleString()," pts away"]}):e.jsx("span",{className:"text-slate-700",children:"Exceeded"}):"â"})]},c)})})]})]})})}const qi={401:"Percent of long-stay residents whose late-loss ADLs (bed mobility, transfer, toileting, eating) worsened compared with their prior assessment. Lower is better.",451:"Percent of long-stay residents whose ability to move around (locomotion) declined since the prior assessment. Lower is better.",481:"Percent of long-stay residents who received an antipsychotic medication. Excludes residents with diagnoses where these meds are clinically indicated (schizophrenia, Tourette's, Huntington's). Lower is better.",479:"Percent of high-risk long-stay residents with one or more Stage 2-4 pressure ulcers. Lower is better.",406:"Percent of long-stay residents with an indwelling urinary catheter. Lower is better.",407:"Percent of long-stay residents who had a urinary tract infection in the prior 30 days. Lower is better.",410:"Percent of long-stay residents who experienced one or more falls with major injury during the look-back period. Lower is better.",551:"Risk-adjusted rate of hospitalizations per 1,000 long-stay resident-days, from Medicare Part A claims. Lower is better.",552:"Risk-adjusted rate of outpatient ED visits per 1,000 long-stay resident-days, from Medicare claims. Lower is better.",434:"Percent of short-stay residents newly started on an antipsychotic medication during the SNF stay (excludes residents already on antipsychotics at admission). Lower is better.",521:"Risk-adjusted percent of short-stay residents who were rehospitalized within 30 days of SNF admission, from Medicare claims. Lower is better.",522:"Risk-adjusted percent of short-stay residents who had an outpatient ED visit within 30 days of SNF admission, from Medicare claims. Lower is better.",S_042:"Risk-adjusted percent of short-stay residents whose discharge function score met or exceeded the CMS expected score, based on MDS GG self-care/mobility items at admission and discharge. Higher is better.",S_005:"Risk-adjusted percent of short-stay residents who were successfully discharged to the community and remained there without an unplanned hospital
4ization or death within 31 days. Higher is better.",S_038:"Percent of short-stay residents who developed a new pressure ulcer or had an existing one worsen during the SNF stay, from MDS skin assessments. Lower is better."},Hi={mds:"MDS â Minimum Data Set. Facility-reported resident assessments submitted every quarter. CMS averages four quarters of resident-level data into a facility-level rate.",claims:"Claims â Medicare fee-for-service claims (Parts A & B). CMS risk-adjusts using resident demographics and pre-stay diagnoses, then publishes a facility-level rate spanning about 12 months of claims data.",qrp:"QRP â SNF Quality Reporting Program. Risk-adjusted measures built from MDS Section GG (function) and Medicare claims at admission and discharge. Published quarterly.",imputed:"State Average (imputed) â the facility did not have enough data to score this measure, so the state average was substituted. CMS uses similar imputation when fewer than 20 assessments are available."};function Ki({ccn:t,facility:s}){const[a,n]=b.useState(null),[r,l]=b.useState(!1),{data:o,isLoading:d}=ee({queryKey:["qm-scorecard",t,r],queryFn:()=>en(t,r?{compare:"true"}:void 0),enabled:!!t});if(d)return e.jsx(Te,{});if(!o)return e.jsx(bt,{text:"No QM scorecard data available."});const{long_stay:c,short_stay:m,overall_total:p,overall_star:i,overall_next_star:h,cms_qm_rating:v,improvement_opportunities:y,overall_state_rank:L,overall_state_total:D}=o,j=[[736,1150,5],[641,735,4],[566,640,3],[466,565,2],[155,465,1]],M=[[720,1150,5],[626,719,4],[526,625,3],[439,525,2],[144,438,1]],f=[[1456,2300,5],[1267,1455,4],[1092,1266,3],[905,1091,2],[299,904,1]],w=(C,u)=>u>0?Math.round(C/u*100):0,B=(C,u)=>{const g=u>0?C/u:0;return g>=.85?"#059669":g>=.6?"#0284c7":g>=.35?"#d97706":"#dc2626"},z=({star:C,label:u,onClick:g})=>e.jsxs("div",{className:"text-center cursor-pointer group",onClick:g,children:[e.jsx("span",{className:"inline-block px-3 py-1 rounded-full text-lg font-bold group-hover:ring-2 ring-sky-300 transition-all",style:C?{backgroundColor:Pe[C]+"1a",color:Pe[C]}:{backgroundColor:"#f1f5f9",color:"#94a3b8"},children:C?`${C} â
`:"â"}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:u}),e.jsx("p",{className:"text-[9px] text-sky-500 opacity-0 group-hover:opacity-100 transition-opacity",children:"View thresholds"})]}),_=({m:C})=>{const u=C.points!=null?w(C.points,C.max_points):0,g=C.points!=null?B(C.points,C.max_points):"#e2e8f0";let A=null;if(C.delta!=null&&C.score!=null&&C.prior_score!=null&&Math.abs(C.prior_score)>1e-6){const F=C.delta/C.prior_score*100,R=F>0?"+":F<0?"â":"",V=Math.abs(F),X=V>=100?V.toFixed(0):(V>=10,V.toFixed(1));A=`${R}${X}%`}else C.delta!=null&&C.prior_score!=null&&Math.abs(C.prior_score)<=1e-6&&C.score!=null&&C.score>0?A="new":C.delta_direction==="flat"&&(A="0%");let x=null;if(C.points!=null&&C.prior_points!=null){const F=C.points-C.prior_points;F!==0&&(x=`${F>0?"+":"â"}${Math.abs(F)} pts`)}const P="text-slate-700",$=qi[C.code],T=Hi[C.source];return e.jsxs("div",{className:"flex items-center gap-3 py-1.5 border-b border-slate-50 last:border-0",children:[e.jsxs("div",{className:"w-44 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700 truncate",title:$||void 0,children:C.label}),e.jsx("p",{className:`text-[10px] ${C.source==="imputed"?"text-amber-500 italic":"text-slate-400"}`,title:T||void 0,children:C.source==="mds"?"MDS":C.source==="claims"?"Claims":C.source==="qrp"?"QRP":C.source==="imputed"?"State Avg (est.)":"N/A"})]}),e.jsxs("div",{className:"w-16 text-right",children:[e.jsx("div",{className:"text-xs font-medium text-slate-700",children:C.display_score||"â"}),A&&e.jsx("div",{className:`text-[9px] leading-tight ${P}`,title:`Was ${C.prior_display_score||"â"} ${C.prior_period_label||""} â relative change (current / prior)`,children:A}),x&&e.jsx("div",{className:`text-[9px] leading-tight ${P}`,title:"CMS QM points change vs prior period â what actually moves the star rating",children:x})]}),e.jsx("div",{className:"flex-1",children:e.jsx("div",{className:"w-full h-3 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${u}%`,backgroundColor:g}})})}),e.jsxs("div",{className:"w-20 text-right",children:[e.jsx("span",{className:"text-xs font-bold",style:{color:g},children:C.points??"â"}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:["/",C.max_points]})]}),C.next_tier?e.jsx("div",{className:"w-24 text-right",children:e.jsxs("span",{className:"text-[10px] text-slate-500",children:["+",C.next_tier.gain," pts if ",C.direction==="lower"?"â":"â"," ",C.max_points<=100?`${(C.next_tier.gap*100).toFixed(1)}%`:`${(C.next_tier.gap*100).toFixed(2)}%`]})}):e.jsx("div",{className:"w-24 text-right",children:e.jsx("span",{className:"text-[10px] text-slate-600 font-medium",children:"Top tier"})})]})},S=({label:C,group:u,adjustedTotal:g})=>e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h3",{className:"text-sm font-bold text-slate-800",children:[C," (",u.measures_available," measures)"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[u.state_rank&&u.state_total&&e.jsxs("span",{className:"text-[11px] text-slate-500",children:["#",u.state_rank," of ",u.state_total," in ",o.state]}),u.star_rating&&e.jsxs("span",{className:"px-2 py-0.5 rounded-full text-xs font-semibold",style:{backgroundColor:Pe[u.
4star_rating]+"1a",color:Pe[u.star_rating]},children:[u.star_rating," â
"]}),e.jsxs("div",{className:"text-right",children:[e.jsx("span",{className:"text-lg font-bold",style:{color:B(u.total_points,u.max_points)},children:u.total_points}),e.jsxs("span",{className:"text-sm text-slate-400",children:["/",u.max_points]}),g!=null&&e.jsxs("p",{className:"text-[10px] text-slate-400",children:["Adjusted: ",g]})]})]})]}),u.measures.map(A=>e.jsx(_,{m:A},A.code)),u.next_star&&e.jsxs("p",{className:"text-[11px] text-slate-500 mt-2 pt-2 border-t border-slate-100",children:["Need ",e.jsxs("strong",{children:[u.next_star.points_needed," more points"]})," for ",u.next_star.next_star," â
"]})]});return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-bold text-slate-800",children:"CMS Five-Star QM Scorecard"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"15 quality measures scored using CMS's published cut points (Table A3, Jan 2025). Points are summed per stay type and combined for the overall QM star rating."}),e.jsxs("label",{className:"inline-flex items-center gap-1.5 mt-1.5 cursor-pointer select-none text-[11px] text-slate-500 hover:text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:r,onChange:C=>l(C.target.checked),className:"w-3 h-3 rounded border-slate-300 text-sky-600 focus:ring-sky-500"}),"Compare to prior period ",e.jsx("span",{className:"text-slate-400",children:"â shows relative change (% improvement or worsening vs prior), color-coded by direction"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 md:gap-6 flex-wrap",children:[e.jsx(z,{star:c.star_rating,label:"Long-Stay",onClick:()=>n("ls")}),e.jsx(z,{star:m.star_rating,label:"Short-Stay",onClick:()=>n("ss")}),e.jsxs("div",{className:"border-l border-slate-200 pl-3 md:pl-6",children:[e.jsx(z,{star:i,label:"Overall QM",onClick:()=>n("overall")}),L&&D&&e.jsxs("p",{className:"text-[11px] font-medium mt-0.5 text-slate-700",children:["#",L," of ",D," in ",o.state]})]}),v&&i!==v&&e.jsxs("div",{className:"text-center",children:[e.jsxs("span",{className:"inline-block px-3 py-1 rounded-full text-lg font-bold",style:{backgroundColor:Pe[v]+"1a",color:Pe[v]},children:[v," â
"]}),e.jsx("p",{className:"text-[11px] text-slate-500 mt-1",children:"CMS Actual"})]})]})]}),v&&i!==v&&e.jsx("div",{className:"mt-3 px-4 py-2.5 rounded-lg bg-amber-50 border border-amber-200",children:e.jsxs("p",{className:"text-xs text-amber-800 leading-relaxed",children:[e.jsxs("strong",{children:["Why does our calculated ",i,"â
differ from CMS's ",v,"â
?"]})," ","CMS imputes missing measures at the assessment level (blending partial facility data with the state average to reach a 20-assessment minimum), while we substitute the full state average when data is unavailable.",i<v?" Our estimate tends to be conservative â CMS's method gives more credit when a facility has partial data.":" CMS may also apply schizophrenia coding audit penalties or use updated cut points (revised every 6 months) that differ from our January 2025 thresholds."]})}),h&&e.jsx("div",{className:"mt-3 px-4 py-2 rounded-lg bg-sky-50 border border-sky-200",children:e.jsxs("p",{className:"text-sm text-sky-800",children:[e.jsxs("strong",{children:[h.points_needed," more points"]})," needed across all measures to reach ",e.jsxs("strong",{children:[h.next_star," â
"]})," overall QM rating."]})})]}),y?.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsx("h3",{className:"text-sm font-bold text-slate-800 mb-3",children:"Improvement Opportunities"}),e.jsx("p",{className:"text-xs text-slate-500 mb-3",children:"Measures closest to the next scoring tier â smallest improvement needed for most points gained."}),e.jsx("div",{className:"space-y-2",children:y.map((C,u)=>e.jsxs("div",{className:"flex items-center gap-3 py-1.5 px-3 rounded-lg bg-slate-50",children:[e.jsxs("span",{className:"text-xs font-bold text-sky-700 w-6",children:[u+1,"."]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-700",children:[C.label," ",e.jsxs("span",{className:"text-slate-400",children:["(",C.stay==="long"?"LS":"SS",")"]})]}),e.jsxs("p",{className:"text-[10px] text-slate-500",children:["Current: ",C.display_score," (",C.current_points," pts) â ",C.direction==="lower"?"Reduce":"Improve"," by ",(C.gap*100).toFixed(2),"% (",C.rel_gap_pct,"% relative change) for ",e.jsxs("strong",{children:["+",C.gain," points"]})]})]}),e.jsxs("span",{className:"text-xs font-bold text-slate-700",children:["+",C.gain," pts"]})]},u))})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsx(S,{label:"Long-Stay Measures",group:c}),e.jsx(S,{label:"Short-Stay Measures",group:m,adjustedTotal:o.short_stay_adjusted_total})]}),e.jsx(Ut,{children:"Scoring based on CMS Five-Star Quality Measure methodology (Te
4chnical Users' Guide, Jan 2025). MDS measures use four-quarter average scores. Claims-based measures (521/522/551/552) use risk-adjusted scores. Discharge Function and Return to Community sourced from SNF QRP. One SS measure (SS Pressure Ulcers) may be missing â CMS imputes this using state averages. Calculated stars may differ slightly from CMS published ratings due to imputation rules and timing."}),a==="ls"&&e.jsx(Ot,{label:"Long-Stay QM",total:c.total_points,max:1150,thresholds:j,onClose:()=>n(null)}),a==="ss"&&e.jsx(Ot,{label:"Short-Stay QM (Adjusted)",total:o.short_stay_adjusted_total,max:1150,thresholds:M,onClose:()=>n(null)}),a==="overall"&&e.jsx(Ot,{label:"Overall QM",total:p,max:2300,thresholds:f,onClose:()=>n(null)})]})}function Wi({diagnosisMix:t}){const[s,a]=b.useState("overall"),n=10,r={overall:{fac:"facility_pct",st:"state_avg",gap:"gap",label:"Overall",blurb:"All residents â combined short-stay and long-stay."},ss:{fac:"facility_pct_ss",st:"state_avg_ss",gap:"gap_ss",label:"Short-Stay",blurb:"Short-stay residents â typically post-acute rehab."},ls:{fac:"facility_pct_ls",st:"state_avg_ls",gap:"gap_ls",label:"Long-Stay",blurb:"Long-stay residents â long-term care population."}},l=r[s],o=[...t].sort((i,h)=>{const v=i[l.fac],y=h[l.fac];return v==null&&y==null?0:v==null?1:y==null?-1:y-v}),d=o.filter(i=>(i[l.fac]??0)>=n||(i[l.st]??0)>=n),c=o.filter(i=>(i[l.fac]??0)<n&&(i[l.st]??0)<n),m=({d:i})=>{const h=i[l.fac],v=i[l.st],y=i[l.gap],L=(i.facilities_reporting??0)<1e3,D=y==null?null:y>1?"up":y<-1?"down":"flat",j=D==="up"||D==="down"?"text-slate-600":"text-slate-400",M=D==="up"?"â²":D==="down"?"â¼":"=";return e.jsxs("tr",{className:"hover:bg-slate-50 border-b border-slate-100",children:[e.jsxs("td",{className:"px-4 py-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs font-medium text-slate-700",children:i.label}),L&&e.jsx("span",{title:`Only ${i.facilities_reporting} facilities nationally report this â interpret with care.`,className:"inline-flex items-center text-[9px] text-slate-500 italic",children:"thin data"})]}),e.jsx("div",{className:"text-[10px] text-slate-400 font-mono",children:i.code})]}),e.jsx("td",{className:"px-3 py-1.5 text-right text-xs font-semibold text-slate-700",children:h!=null?`${h.toFixed(1)}%`:e.jsx("span",{className:"text-slate-300",children:"â"})}),e.jsx("td",{className:"px-3 py-1.5 text-right text-xs text-slate-500",children:v!=null?`${v.toFixed(1)}%`:e.jsx("span",{className:"text-slate-300",children:"â"})}),e.jsx("td",{className:`px-3 py-1.5 text-right text-xs font-medium ${j}`,children:y!=null?`${y>0?"+":""}${y}% ${M}`:e.jsx("span",{className:"text-slate-300",children:"â"})})]})},p=()=>e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-4 py-1.5 text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"Condition"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"Facility"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"State avg"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"vs state"})]})});return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-1 gap-3",children:[e.jsx("h3",{className:"text-sm font-bold text-slate-800",children:"Patient Profile / Diagnosis Mix"}),e.jsx("div",{className:"inline-flex rounded-lg border border-slate-200 overflow-hidden text-[11px] flex-shrink-0",children:Object.entries(r).map(([i,h])=>e.jsx("button",{onClick:()=>a(i),className:`px-2.5 py-1 font-medium transition-colors ${s===i?"bg-sky-600 text-white":"bg-white text-slate-600 hover:bg-slate-50"}`,children:h.label},i))})]}),e.jsxs("p",{className:"text-xs text-slate-500 mb-4",children:["Active diagnoses prevalence â ",l.blurb," Useful for referral targeting, program development, and understanding clinical case mix."]}),e.jsxs("div",{className:"mb-4",children:[e.jsxs("h4",{className:"text-xs font-semibold text-slate-700 mb-1",children:["Common conditions ",e.jsxs("span",{className:"text-slate-400 font-normal",children:["(â¥",n,"% of ",l.label.toLowerCase()," residents)"]})]}),d.length===0?e.jsxs("p",{className:"text-xs text-slate-400 italic py-2",children:["No conditions reach the ",n,"% threshold for ",l.label.toLowerCase()," residents at this facility."]}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx(p,{}),e.jsx("tbody",{children:d.map(i=>e.jsx(m,{d:i},i.code))})]})]}),c.length>0&&e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"cursor-pointer text-xs font-semibold text-slate-700 hover:text-sky-700 select-none list-none",children:[e.jsx("span",{className:"inline-block transition-transform group-open:rotate-90",children:"â¶"}
4)," Other conditions ",e.jsxs("span",{className:"text-slate-400 font-normal",children:["(",c.length," below ",n,"%)"]})]}),e.jsxs("table",{className:"w-full text-sm mt-2",children:[e.jsx(p,{}),e.jsx("tbody",{children:c.map(i=>e.jsx(m,{d:i},i.code))})]})]})]})}const Vi={Extensive:"#0e7490",Diagnosis:"#0284c7",Nutrition:"#d97706",Skin:"#dc2626",Bladder:"#64748b"};function Qi({ccn:t}){const{data:s,isLoading:a}=ee({queryKey:["nta-scorecard",t],queryFn:()=>tn(t),enabled:!!t}),{data:n}=ee({queryKey:["competitors-radius-only",t,15],queryFn:()=>Gs(t,{radius_miles:15}),enabled:!!t}),[r,l]=b.useState(!1),o=b.useMemo(()=>{const y=n?.results||[],L=s?.state_scores||{};return y.length?y.map(D=>({ccn:D.ccn,name:D.provider_name,distance:D.distance_miles,score:L[D.ccn]??null})).filter(D=>D.score!=null):[]},[n,s]);if(a)return e.jsx(Te,{});if(!s?.items)return e.jsx(bt,{text:"No NTA coding data available."});const{items:d,opportunities:c,total_weighted_score:m,report_date:p,state_rank:i,state_total:h,state_stats:v}=s;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-bold text-slate-800",children:"Clinical Acuity Index"}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:["Facility-level prevalence of PDPM NTA (Non-Therapy Ancillary) comorbidity conditions compared to state peers. Higher scores indicate a more clinically complex resident population.",p&&e.jsxs("span",{className:"ml-1 text-slate-400",children:["· MDS quarter: ",new Date(p+"T00:00:00").toLocaleDateString("en-US",{month:"short",year:"numeric"})," · Overall (all residents)"]})]})]}),e.jsxs("div",{className:"text-center flex-shrink-0 ml-4",children:[e.jsx("span",{className:"inline-block px-4 py-2 rounded-full text-2xl font-bold bg-slate-100 text-slate-800",children:m}),e.jsx("p",{className:"text-[10px] text-slate-500 mt-1",children:"Acuity Index"}),i&&h&&e.jsxs("p",{className:"text-[11px] font-medium mt-0.5 text-slate-700",children:["#",i," of ",h," in ",s.state]})]})]}),v&&(()=>{const y=[{val:v.p10,pos:0},{val:v.p25,pos:25},{val:v.p50,pos:50},{val:v.p75,pos:75},{val:v.p90,pos:100}],L=M=>{if(M<=y[0].val)return 0;if(M>=y[y.length-1].val)return 100;for(let f=1;f<y.length;f++)if(M<=y[f].val){const w=y[f].val-y[f-1].val||1,B=(M-y[f-1].val)/w;return y[f-1].pos+B*(y[f].pos-y[f-1].pos)}return 100},D=[{label:"25th",value:v.p25,pos:25},{label:"Median",value:v.p50,pos:50},{label:"75th",value:v.p75,pos:75}],j=Math.min(98,Math.max(2,L(m)));return e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-[10px] text-slate-400",children:"Lower acuity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[o?.length>0&&e.jsxs("button",{onClick:()=>l(!r),className:`text-[10px] font-medium px-2 py-0.5 rounded-full border transition-colors ${r?"bg-sky-50 border-sky-300 text-sky-700":"border-slate-300 text-slate-500 hover:border-sky-300"}`,children:[r?"Hide":"Show"," Competitors (",o.length,")"]}),e.jsx("span",{className:"text-[10px] text-slate-400",children:"Higher acuity"})]})]}),e.jsxs("div",{className:"relative mb-8",style:{height:r?"3rem":"2rem"},children:[e.jsx("div",{className:"absolute inset-x-0 top-1 h-6 rounded-full bg-sky-100"}),D.map(M=>e.jsxs("div",{className:"absolute",style:{left:`${M.pos}%`,top:0},children:[e.jsx("div",{className:"absolute top-1 h-6 border-l-[1.5px] border-dashed border-slate-400/60"}),e.jsxs("div",{className:"absolute top-[30px] text-[9px] font-medium text-slate-500 whitespace-nowrap",style:{transform:"translateX(-50%)"},children:[M.label,": ",M.value]})]},M.label)),r&&(()=>{const M=o.map(w=>({...w,cp:Math.min(98,Math.max(2,L(w.score)))}));M.sort((w,B)=>w.cp-B.cp);const f=[];return M.forEach(w=>{const B=f.filter(_=>Math.abs(_.cp-w.cp)<3),z=B.length%2===0?-6*((B.length+2)/2):6*((B.length+1)/2);f.push({...w,yOffset:z})}),f.map(w=>e.jsx("div",{className:"absolute",style:{left:`${w.cp}%`,top:`${14+w.yOffset}px`},title:`${w.name}: ${w.score} (${w.distance} mi)`,children:e.jsx("div",{className:"w-3.5 h-3.5 -translate-x-1/2 -translate-y-1/2 roun
4ded-full bg-amber-400 border-2 border-white shadow cursor-pointer hover:scale-150 transition-transform z-10"})},w.ccn))})(),e.jsxs("div",{className:"absolute",style:{left:`${j}%`,top:0},children:[e.jsx("div",{className:"absolute -translate-x-1/2 -top-1.5 w-0 h-0",style:{borderLeft:"7px solid transparent",borderRight:"7px solid transparent",borderTop:"8px solid #0f172a"}}),e.jsx("div",{className:"absolute -translate-x-[1px] top-[6px] w-[3px] h-[22px] bg-slate-900 rounded-full"}),e.jsx("div",{className:"absolute -translate-x-1/2 -top-[20px] bg-slate-900 text-white text-[10px] font-bold px-2 py-0.5 rounded whitespace-nowrap shadow",children:m})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-[10px] text-slate-400",children:["P10: ",v.p10]}),e.jsxs("span",{className:"text-[10px] text-slate-400",children:["P90: ",v.p90]})]})]})})()]}),c?.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5",children:[e.jsx("h3",{className:"text-sm font-bold text-slate-800 mb-3",children:"Acuity Variance from State Average"}),e.jsx("p",{className:"text-xs text-slate-500 mb-3",children:"Conditions where this facility's prevalence differs notably from the state average. Variances may reflect differences in resident population, clinical acuity, or documentation practices."}),e.jsx("div",{className:"space-y-2",children:c.map(y=>e.jsxs("div",{className:"flex items-center gap-3 py-1.5 px-3 rounded-lg bg-slate-50",children:[e.jsxs("span",{className:"text-xs font-bold text-slate-600 w-5",children:[y.points,"pt"]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700",children:y.label}),e.jsxs("p",{className:"text-[10px] text-slate-500",children:["Facility: ",y.facility_pct?.toFixed(1),"% · State avg: ",y.state_avg?.toFixed(1),"% · Variance: ",y.gap>0?"+":"",y.gap,"%"]})]})]},y.code))})]}),s.diagnosis_mix?.length>0&&e.jsx(Wi,{diagnosisMix:s.diagnosis_mix}),(()=>{const y=d.filter(f=>f.facility_pct!=null||f.state_avg!=null).sort((f,w)=>(w.state_avg??-1)-(f.state_avg??-1)),L=y.filter(f=>(f.facility_pct??0)>=1||(f.state_avg??0)>=1),D=y.filter(f=>(f.facility_pct??0)<1&&(f.state_avg??0)<1),j=d.filter(f=>f.facility_pct==null&&f.state_avg==null),M=({rows:f})=>e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-4 py-2 text-xs font-semibold text-slate-500",children:"Item"}),e.jsx("th",{scope:"col",className:"text-center px-3 py-2 text-xs font-semibold text-slate-500",children:"Pts"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 text-xs font-semibold text-slate-500",children:"Type"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-2 text-xs font-semibold text-slate-500",children:"Facility %"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-2 text-xs font-semibold text-slate-500",children:"State Avg"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-2 text-xs font-semibold text-slate-500",children:"Variance"}),e.jsx("th",{scope:"col",className:"px-3 py-2 w-24"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:f.map(w=>e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsxs("td",{className:"px-4 py-2",children:[e.jsx("p",{className:"text-xs font-medium text-slate-700",children:w.label}),e.jsx("p",{className:"text-[10px] text-slate-400 font-mono",children:w.code})]}),e.jsx("td",{className:"px-3 py-2 text-center",children:e.jsx("span",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-semibold ${w.points>=4?"bg-sky-100 text-sky-700":"bg-slate-100 text-slate-600"}`,children:w.points})}),e.jsx("td",{className:"px-3 py-2 text-[10px] font-medium",style:{color:Vi[w.category]||"#64748b"},children:w.category}),e.jsx("td",{className:"px-3 py-2 text-right font-semibold text-xs tabular-nums",children:w.facility_pct!=null?`${w.facility_pct.toFixed(1)}%`:"â"}),e.jsx("td",{className:"px-3 py-2 text-right text-xs tabular-nums text-slate-500",children:w.state_avg!=null?`${w.state_avg.toFixed(1)}%`:"â"}),e.jsx("td",{className:"px-3 py-2 text-right text-xs tabular-nums font-medium text-slate-600",children:w.gap!=null?`${w.gap>0?"+":""}${w.gap}%`:"â"}),e.jsx("td",{className:"px-3 py-2",children:(w.facility_pct!=null||w.state_avg!=null)&&e.jsxs("div",{className:"w-full h-2 bg-slate-100 rounded-full overflow-hidden relative",children:[e.jsx("div",{className:"absolute h-full bg-sky-500 rounded-full",style:{width:`${Math.min(100,w.facility_pct??0)}%`}}),w.state_avg!=null&&e.jsx("div",{className:"absolute h-full w-0.5 bg-slate-400",style:{left:`${Math.min(100,w.state_avg)}%`},title:`State avg: ${w.state_avg}%`})]})})]},w.code))})]});return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 py-3 border-b border-slate-200",children:e.jsxs("p",{className:"text-sm font-semibold text-slate-700",children:["NTA Comorbidity Items with Data (",L.length,")"]})}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx(M,{rows:L})})]}),(D.length>0||j.length>0)&&e.jsxs("details",{className:"bg-white rounded-xl border border-slate-200 shadow-sm",children:[e.jsxs("summary",{className:"px-4 py-3 text-sm font-semibold text-slate-500 cursor-pointer hover:bg-slate-50 select-none",children:["Rarely captured items (",D.length+j.length,") â under 1% prevalence or no data"]}),e.jsx("div",{className:"overflow-x-auto border-t border-slate-100",children:e.jsx(M,{rows:[...D,...j]})})]})]})})(),e.jsxs(Ut,{children:["Acuity index derived from facility-level prevalence of PDPM NTA comorbidity conditions (CMS Fact Sheet v2, Feb 2019) using MDS 3.0 quarterly assessments. This is a comparative metric â not an actual NTA tier classification. PDPM NTA scoring is per-resident, requiring individual-level data not available publicly. Variances reflect differences in resident population and clinical acuity across facilities for informational purposes only.",e.jsx("br",{}),e.jsx("br",{}),e.jsx("strong",{children:"Scope note:"})," This scorecard reflects MDS-coded NTA conditions only. Roughly half of the official PDPM NTA list is claims-based (HIV/AIDS [8 pts â highest weight], cardio-respiratory failure & shock [3 pts], lung/major-organ transplants, endocarditis, immune disorders, end-stage liver disease, cystic fibrosis, morbid obesity, and others). These cannot be captured from public MDS data, and a facility heavy in those conditions will be under-scored relative to its true PDPM NTA tier."]})]})}const Cs=[{code:"S_041_01_OBS_RATE",short:"% at or Above Expected Self-Care at Discharge",dir:"higher",star:!1},{code:"S_042_02_OBS_RATE",short:"% at or Above Expected Mobility at Discharge",dir:"higher",star:!1},{code:"S_024_06_OBS_RATE",short:"% Who Made Improvements in Self-Care",dir:"higher",star:!1},{code:"S_025_06_OBS_RATE",short:"% Who Made Improvements in Mobility",dir:"higher",star:!1},{code:"S_005_02_DTC_RS_RATE",short:"Rate of Successful Return to Community",dir:"higher",star:!0},{code:"S_004_01_PPR_PD_RSRR",short:"Risk-Standardized Potentially Preventable Readmission Rate",dir:"lower",star:!0},{code:"S_038_02_OBS_RATE",short:"% Experiencing Falls with Major Injury",dir:"lower",star:!1},{code:"S_039_01_HAI_RS_RATE",short:"Risk-Standardized Healthcare-Associated Infection Rate",dir:"lower",star:!0},{code:"S_013_02_OBS_RATE",short:"% with Moderate to Severe Pain (Short-Stay)",dir:"lower",star:!1},{code:"S_007_02_OBS_RATE",short:"% Whose Medication Regimen Was Reviewed",dir:"higher",star:!1}],Yi=t=>Za(t?.start_date,t?.end_date);function Gi({ccn:t,facility:s}){const{data:a,isLoading:n}=ee({queryKey:["facility-qrp",t,s?.state],queryFn:()=>sn({state:s?.state}),enabled:!!s?.state}),r=a?.facilities?.find(o=>o.ccn===t),l=b.useMemo(()=>
4{if(!a?.facilities)return{};const o={},d=a.facilities.filter(c=>c.measures);return Cs.forEach(c=>{const m=d.filter(i=>i.measures[c.code]!=null).map(i=>({ccn:i.ccn,val:i.measures[c.code]}));if(!m.length)return;m.sort((i,h)=>c.dir==="higher"?h.val-i.val:i.val-h.val);const p=m.findIndex(i=>i.ccn===t);p>=0&&(o[c.code]={rank:p+1,total:m.length})}),o},[a,t]);return n?e.jsx(Te,{}):r?e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wide text-slate-500",children:[e.jsx("th",{scope:"col",className:"text-left font-semibold px-4 py-2.5",children:"Measure"}),e.jsx("th",{scope:"col",className:"text-left font-semibold px-3 py-2.5 whitespace-nowrap",children:"CMS period"}),e.jsx("th",{scope:"col",className:"text-right font-semibold px-3 py-2.5 whitespace-nowrap",children:"This SNF"}),e.jsxs("th",{scope:"col",className:"text-right font-semibold px-3 py-2.5 whitespace-nowrap",children:[s?.state||"State"," med."]}),e.jsx("th",{scope:"col",className:"text-right font-semibold px-3 py-2.5",children:"National"}),e.jsx("th",{scope:"col",className:"text-right font-semibold px-3 py-2.5",children:"Rank"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:Cs.map(o=>{const d=r.measures?.[o.code],c=a.measures?.find(v=>v.code===o.code),m=c?.national_median,p=c?.state_median,i=l[o.code],h=d!=null&&m!=null?o.dir==="higher"?d>m:d<m:null;return e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsxs("td",{className:"px-4 py-2 text-slate-700",children:[o.short,o.star&&e.jsx("span",{className:"text-amber-400 text-[10px] ml-1",title:"Impacts CMS star rating or SNF VBP",children:"â
"})]}),e.jsx("td",{className:"px-3 py-2 text-[11px] text-slate-400 whitespace-nowrap tabular-nums",title:c?.start_date?`CMS reporting period ${c.start_date} to ${c.end_date}`:void 0,children:Yi(c)}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums font-semibold text-slate-800 whitespace-nowrap",children:d!=null?e.jsxs(e.Fragment,{children:[d.toFixed(1),"%",h!=null&&e.jsx("span",{className:`ml-1 text-[10px] ${h?"text-slate-500":"text-slate-300"}`,title:h?"Better than the national median":"At or below the national median",children:h?"â²":"â¼"})]}):"â"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-slate-500",children:p!=null?`${p}%`:"â"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-slate-500",children:m!=null?`${m}%`:"â"}),e.jsx("td",{className:"px-3 py-2 text-right tabular-nums text-sky-600 font-medium whitespace-nowrap",children:i?`#${i.rank} of ${i.total}`:"â"})]},o.code)})})]})})}),e.jsxs("p",{className:"text-[10px] text-slate-400 italic",children:["SNF Quality Reporting Program measures. â²/â¼ = better / at-or-below the national median (measure direction accounted for). â
= impacts CMS star rating or SNF VBP. Rank is within ",s?.state,".",a?.periods_vary?" CMS reports these measures over different windows, so each row shows its own reporting period â rows are not directly comparable to each other.":"",a?.period_max_end?` Most recent data through ${Ja(a.period_max_end)}.`:""]})]}):e.jsx(bt,{text:"No QRP outcome data available for this facility."})}function Ui({ccn:t,facility:s}){const[a,n]=b.useState("health"),[r,l]=b.useState([]),[o,d]=b.useState(!1),[c,m]=b.useState("overall"),[p,i]=b.useState(!0),[h,v]=b.useState(""),[y,L]=b.useState(!1),[D,j]=b.useState(null),[M,f]=b.useState("asc"),[w,B]=b.useState(""),z=s?.state,{data:_,isLoading:S}=ee({queryKey:["facility-mds-summary",t],queryFn:()=>an(t),enabled:!!t});b.useEffect(()=>{if(!o&&_?.items?.length){const G=["J1100C","I2900","I5600","I6200"].map(J=>_.items.find(Z=>Z.mds_item?.startsWith(J))?.mds_item).filter(Boolean);G.length&&l(G),d(!0)}},[_,o]);const C=ta({queries:r.map(O=>({queryKey:["facility-mds-item",t,O,z,p],queryFn:()=>Xa(t,{mds_item:O,state:p?z:void 0}),enabled:!0,staleTime:300*1e3}))});C.some(O=>O.isLoading);const u=O=>
4{if(O==null||O===""||O==="."||O==="_")return null;const G=Number(O);return isNaN(G)?null:G},g=O=>{const[G,J]=(O||"").split("-");return!G||!J?O||"":`Q${Math.floor((Number(J)-1)/3)+1} ${G.slice(2)}`},A=O=>{const G=O.indexOf(":");return G<0?{code:"",desc:O}:{code:O.slice(0,G),desc:O.slice(G+2)}},x=c==="long"?"long_stay_percent":c==="short"?"short_stay_percent":"overall_percent",P=O=>{if(!O?.length)return null;if(O.includes("Yes"))return"Yes";if(O.length===2){const G=O.find(J=>J!=="No"&&J!=="0"&&!J.startsWith("No "));if(G)return G}return[...O].sort()[0]},$=b.useMemo(()=>{if(!_?.items)return[];const O=Lt.find(N=>N.key===a);if(!O)return[];const G=N=>c==="long"?N.long_stay_percent:c==="short"?N.short_stay_percent:N.overall_percent,J=N=>c==="long"?N.last_long_stay:c==="short"?N.last_short_stay:N.last_overall;let Z=_.items.filter(N=>N.mds_item&&zi(N.mds_item,O));const se=h.trim().toLowerCase();return se&&(Z=Z.filter(N=>N.mds_item.toLowerCase().includes(se))),Z.map(N=>{const Y=(N.sparkline||[]).map(U=>G(U)).filter(U=>U!=null);return{name:N.mds_item,responses:N.responses||[],primary:N.primary,sparkline:Y,lastValue:J(N)}})},[_,a,h,c]),T=b.useMemo(()=>{const O=[],G=new Map((_?.items||[]).map(J=>[J.mds_item,J]));for(let J=0;J<r.length;J++){const Z=r[J],se=G.get(Z),N=C[J]?.data,Y=C[J]?.isLoading,U=se?.primary||(N?.results?.length?P([...new Set(N.results.map(E=>E.mds_response).filter(Boolean))]):null),H=new Map;if(se?.sparkline?.length)for(const E of se.sparkline){const W=c==="long"?E.long_stay_percent:c==="short"?E.short_stay_percent:E.overall_percent;E.date&&W!=null&&H.set(E.date,{date:E.date,facility:Number(W)})}else if(N?.results?.length&&U)for(const E of N.results){if(E.mds_response!==U)continue;const W=E.report_date?.slice(0,7);if(!W)continue;const te=u(E[x]);te!=null&&(H.has(W)||H.set(W,{date:W}),H.get(W).facility=te)}if(p&&N?.state_medians&&U)for(const E of N.state_medians){if(E.mds_response!==U)continue;const W=E.report_date?.slice(0,7);if(!W)continue;const te=u(E[x]);te!=null&&(H.has(W)||H.set(W,{date:W}),H.get(W).state=te)}const ae=[...H.values()].sort((E,W)=>(E.date||"").localeCompare(W.date||"")),I=[...ae].reverse().find(E=>E.facility!=null);O.push({itemName:Z,data:ae,primary:U,lastValue:I?.facility??null,loadingState:p&&Y})}return O},[JSON.stringify(C.map(O=>O.dataUpdatedAt)),c,p,r,_]),F=["#0284c7","#64748b","#0ea5e9","#94a3b8","#0891b2","#475569","#38bdf8","#06b6d4","#7dd3fc","#334155","#22d3ee","#cbd5e1","#0369a1","#7c8ba1","#155e75","#a5b4c4"],R=O=>{l(G=>G.includes(O)?G.filter(J=>J!==O):[...G,O])},V=({values:O,color:G="#94a3b8"})=>{if(!O||O.length<2)return null;const J=60,Z=16,se=Math.min(...O),Y=Math.max(...O)-se||1,U=O.map((H,ae)=>{const I=ae/(O.length-1)*J,E=Z-(H-se)/Y*Z;return`${ae===0?"M":"L"}${I.toFixed(1)},${E.toFixed(1)}`}).join(" ");return e.jsx("svg",{width:J,height:Z,className:"block",children:e.jsx("path",{d:U,fill:"none",stroke:G,strokeWidth:"1.5"})})};if(S)return e.jsx(Te,{});if(!_?.items?.length)return e.jsx(bt,{text:"No MDS data available for this facility."});const X=C.flatMap((O,G)=>(O.data?.results||[]).map(J=>({...J,_itemCode:A(r[G]).code})));return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 p-3 shadow-sm",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Kr,{size:12,className:"text-slate-400"}),e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-medium",children:"Pinned"}),r.length===0&&e.jsx("span",{className:"text-xs text-slate-400 italic",children:"Click items to pin them â pins persist across category tabs."}),r.map((O,G)=>{const{code:J,desc:Z}=A(O);return e.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-slate-100 text-slate-700 text-xs px-2 py-0.5 rounded-full border border-slate-200",children:[e.jsx("span",{className:"w-2 h-2 rounded-full",style:{backgroundColor:F[G%F.length]}}),e.jsx("span",{className:"font-medium truncate max-w-[200px]",title:Z,children:Z}),e.jsx("span",{className:"text-slate-400 hidden md:inline",children:"·"}),e.jsx("span",{className:"text-slate-400 hidden md:inline",children:J}),e.jsx("button",{onClick:()=>R(O),"aria-label":`Remove ${Z}`,className:"hover:text-red-500 ml-0.5",children:e.jsx(Me,{size:11})})]},O)}),r.length>1&&e.jsx("button",{onClick:()=>l([]),className:"text-[10px] text-slate-400 hover:text-red-500 transition-colors ml-2",children:"Clear all"})]})}),e.jsx("div",{className:"flex flex-wrap gap-1",children:Lt.filter(O=>O.prefix!==null).map(O=>e.jsx("button",{onClick:()=>{n(O.key),v("")},className:`px-2 py-1 text-[11px] font-medium rounded-lg whitespace-nowrap transition-colors ${a===O.key?"bg-sky-100 text-sky-700":"bg-slate-100 text-slate-500 hover:bg-slate-200"}`,title:`${O.label} â ${O.desc}`,children:O.short},O.key))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsx("div",{className:"lg:col-span-1",children:e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"px-3 py-2 border-b border-slate-200 bg-slate-50 flex items-center gap-2",children:[e.jsx(Jt,{size:12,className:"text-slate-400 flex-shrink-0"}),e.jsx("input",{value:h,onChange:O=>v(O.target.value),placeholder:`Search ${Lt.find(O=>O.key===a)?.label}â¦`,className:"flex-1 text-xs bg-transparent focus:outline-none placeholder-slate-400"}),h&&e.jsx("button",{onClick:()=>v(""),className:"text-slate-400 hover:text-slate-700",children:e.jsx(Me,{size:12})})]}),e.jsxs("div",{className:"px-3 py-1.5 border-b border-slate-100 flex items-center justify-between bg-white",children:[e.jsxs("p",{className:"text-[10px] text-slate-400",children:[$.length," item",$.length!==1?"s":""]}),e.jsx("p",{className:"text-[10px] text-slate-400",children:"Latest · Trend"})]}),e.jsxs("div",{className:"divide-y divide-slate-100 max-h-[640px] overflow-y-auto",children:[$.map(O=>{const{code:G,desc:J}=A(O.name),Z=r.includes(O.name);return e.jsx("button",{onClick:()=>R(O.name),className:`w-full text-left px-3 py-2 text-sm transition-colors ${Z?"bg-sky-50 border-l-2 border-sky-500":"hover:bg-slate-50 border-l-2 border-transparent"}`,children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:`mt-0.5 w-3.5 h-3.5 rounded border flex-shrink-0 flex items-center justify-center text-[10px] ${Z?"bg-sky-500 border-sky-500 text-white":"border-slate-300"}`,children:Z&&"â"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:`font-medium leading-tight ${Z?"text-sky-700":"text-slate-700"}`,children:J}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-0.5",children:G})]}),e.jsxs("div",{className:"flex flex-col items-end gap-0.5 flex-shrink-0",children:[O.lastValue!=null&&e.jsxs("span",{className:"text-xs font-semibold text-slate-700",children:[Number(O.lastValue).toFixed(1),"%"]}),e.jsx(V,{values:O.sparkline,color:"#94a3b8"})]})]})},O.name)}),$.length===0&&e.jsx("p",{className:"px-3 py-6 text-xs text-slate-400 text-center",children:h?`No items match "${h}"`:"No items in this category"})]})]})}),e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[r.length===0&&e.jsx("div",{className:"bg-slate-50 border border-slate-200 rounded-xl p-8 text-center",children:e.jsx("p",{className:"text-sm text-slate-500",children:"Click items in the list to pin them â they'll show up here as small chart cards."})}),r.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("div",{className:"flex gap-1 bg-slate-100 rounded-lg p-0.5",children:[{key:"overall",label:"Overall"},{key:"long",label:"Long Stay"},{key:"short",label:"Short Stay"}].map(O=>e.jsx("button",{onClick:()=>m(O.key),className:`px-3 py-1 text-xs font-medium rounded-md transition-colors ${c===O.key?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:O.label},O.key))}),z&&e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-slate-500 cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:O=>i(O.target.checked),className:"accent-sky-500"}
4),"Show ",z," state median"]}),e.jsx("span",{className:"ml-auto text-[10px] text-slate-400",children:"Showing primary response per item"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:T.map((O,G)=>{const{code:J,desc:Z}=A(O.itemName),se=F[G%F.length],N=O.data,Y=N.some(U=>U.state!=null);return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4 relative",children:[e.jsx("button",{onClick:()=>R(O.itemName),className:"absolute top-2 right-2 text-slate-300 hover:text-red-500",title:"Unpin",children:e.jsx(Me,{size:14})}),e.jsxs("div",{className:"flex items-start gap-2 mb-2 pr-6",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full mt-1.5 flex-shrink-0",style:{backgroundColor:se}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800 leading-tight truncate",title:Z,children:Z}),e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:[J,O.primary?` · Response: ${O.primary}`:""]})]})]}),O.lastValue!=null&&e.jsxs("p",{className:"text-2xl font-bold text-slate-800 mb-2",children:[Number(O.lastValue).toFixed(1),"%"]}),N.length>0?e.jsx(je,{width:"100%",height:140,children:e.jsxs($e,{data:N,margin:{top:5,right:8,bottom:0,left:-12},children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:9},interval:"preserveStartEnd",tickFormatter:g}),e.jsx(xe,{tick:{fontSize:9},tickFormatter:U=>U+"%",width:48}),e.jsx(ce,{formatter:(U,H)=>[U!=null?`${Number(U).toFixed(1)}%`:"NA",H==="facility"?"This facility":"State median"],labelFormatter:g,contentStyle:{fontSize:11}}),e.jsx(oe,{type:"monotone",dataKey:"facility",stroke:se,strokeWidth:2,dot:{r:2.5},connectNulls:!0}),p&&Y&&e.jsx(oe,{type:"monotone",dataKey:"state",stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"5 3",dot:!1,connectNulls:!0})]})}):O.loading?e.jsx("div",{className:"flex items-center justify-center py-8 text-slate-400",children:e.jsx(ge,{className:"animate-spin",size:16})}):e.jsx("p",{className:"text-xs text-slate-400 italic py-6 text-center",children:"No data for selected stay type"})]},O.itemName)})}),X.length>0&&e.jsx("div",{children:e.jsxs("button",{onClick:()=>L(O=>!O),className:"text-xs text-slate-500 hover:text-sky-600 flex items-center gap-1",children:[y?"â¾":"â¸"," ",y?"Hide":"Show"," raw data table (",X.length," rows)"]})}),y&&X.length>0&&(()=>{const O=r.length>1,G=[...O?[{key:"_itemCode",label:"Item"}]:[],{key:"report_date",label:"Quarter"},{key:"mds_response",label:"Response"},{key:"overall_percent",label:"Overall %",right:!0},{key:"total_residents",label:"Residents",right:!0},{key:"long_stay_percent",label:"Long Stay %",right:!0},{key:"long_stay_residents",label:"Long Res.",right:!0},{key:"short_stay_percent",label:"Short Stay %",right:!0},{key:"short_stay_residents",label:"Short Res.",right:!0}],J=[...new Set(X.map(H=>H.mds_response).filter(Boolean))].sort(),Z=w?X.filter(H=>H.mds_response===w):X,se=D?[...Z].sort((H,ae)=>{let I=H[D],E=ae[D];return D==="report_date"?(I=I||"",E=E||""):G.find(W=>W.key===D)?.right?(I=u(I)??-1/0,E=u(E)??-1/0):(I=(I||"").toString().toLowerCase(),E=(E||"").toString().toLowerCase()),I<E?M==="asc"?-1:1:I>E?M==="asc"?1:-1:0}):Z,N=H=>{D===H?f(ae=>ae==="asc"?"desc":"asc"):(j(H),f("asc"))},Y=()=>{const H=G.map(E=>E.label).join(","),ae=se.map(E=>G.map(W=>{let te=W.key==="report_date"?E[W.key]?.slice(0,7)??"":E[W.key]??"";return te==="."&&(te=""),`"${String(te).replace(/"/g,'""')}"`}).join(",")),I=[H,...ae].join(` 5`);Ys(`MDS_${t}_${r.map(E=>A(E).code).join("_")}.csv`,I)},U=H=>H!=null&&H!=="."&&H!=="_"?H:"â";return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-slate-200 bg-slate-50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-slate-500",children:[se.length," rows"]}),J.length>1&&e.jsxs("select",{value:w,onChange:H=>B(H.target.value),className:"text-xs border border-slate-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-sky-500",children:[e.jsx("option",{value:"",children:"All Responses"}),J.map(H=>e.jsx("option",{value:H,children:H},H))]})]}),e.jsxs("button",{onClick:Y,className:"flex items-center gap-1 text-xs text-slate-500 hover:text-sky-600 transition-colors",children:[e.jsx(Ue,{size:12})," Export CSV"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsx("tr",{children:G.map(H=>e.jsxs("th",{scope:"col",onClick:()=>N(H.key),className:`px-3 py-2 text-xs font-semibold text-slate-500 uppercase tracking-wide cursor-pointer hover:text-slate-800 select-none whitespace-nowrap ${H.right?"text-right":"text-left"}`,children:[H.label,D===H.key&&e.jsx("span",{className:"ml-1 text-sky-500",children:M==="asc"?"â²":"â¼"})]},H.key))})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:se.map((H,ae)=>e.jsxs("tr",{className:"hover:bg-slate-50",children:[O&&e.jsx(ne,{children:e.jsx("span",{className:"text-xs font-mono text-sky-600",children:H._itemCode})}),e.jsx(ne,{mono:!0,children:H.report_date?.slice(0,7)}),e.jsx(ne,{children:H.mds_response??"â"}),e.jsx(ne,{right:!0,children:U(H.overall_percent)}
5),e.jsx(ne,{right:!0,children:U(H.total_residents)}),e.jsx(ne,{right:!0,children:U(H.long_stay_percent)}),e.jsx(ne,{right:!0,children:U(H.long_stay_residents)}),e.jsx(ne,{right:!0,children:U(H.short_stay_percent)}),e.jsx(ne,{right:!0,children:U(H.short_stay_residents)})]},ae))})]})})]})})()]})]})]})]})}function Ji({open:t,onClose:s,rows:a=[],summary:n,providerName:r}){const l=De(s,{enabled:t});return t?e.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-slate-900/40 p-4",onClick:s,children:e.jsxs("div",{ref:l,role:"dialog","aria-modal":"true","aria-labelledby":"fire-safety-title",className:"w-full max-w-3xl max-h-[82vh] overflow-y-auto rounded-xl bg-white shadow-xl",onClick:o=>o.stopPropagation(),children:[e.jsxs("div",{className:"sticky top-0 flex items-start justify-between gap-3 border-b border-slate-200 bg-white px-5 py-3.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sl,{size:16,className:"flex-shrink-0 text-slate-500","aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("div",{id:"fire-safety-title",className:"text-sm font-semibold text-slate-800",children:"Fire safety citations"}),e.jsxs("div",{className:"text-xs text-slate-500",children:[r?`${r} â `:"",n?.total_citations??a.length," across ",n?.unique_surveys??0," survey",(n?.unique_surveys??0)!==1?"s":""]})]})]}),e.jsx(ts,{onClick:s,size:18,className:"text-slate-400 hover:text-slate-700"})]}),e.jsxs("div",{className:"p-5",children:[a.length===0?e.jsx("p",{className:"text-sm text-slate-400",children:"No fire safety citations on record for this facility."}):e.jsx("div",{className:"overflow-x-auto border border-slate-200 rounded-lg",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-3 py-2 font-medium text-slate-500 whitespace-nowrap",children:"Date"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 font-medium text-slate-500 whitespace-nowrap",children:"Tag"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 font-medium text-slate-500 whitespace-nowrap",children:"Code"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-2 font-medium text-slate-500",children:"Reason"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:a.map((o,d)=>{const c=d===0||o.survey_date!==a[d-1].survey_date;return e.jsxs("tr",{className:`hover:bg-slate-50 ${c&&d>0?"border-t-slate-200":""}`,children:[e.jsx("td",{className:"px-3 py-2 tabular-nums whitespace-nowrap align-top text-slate-600",children:c?o.survey_date:""}),e.jsxs("td",{className:"px-3 py-2 font-mono whitespace-nowrap align-top text-slate-700",children:[o.deficiency_prefix,o.deficiency_tag_number]}),e.jsx("td",{className:"px-3 py-2 align-top",children:o.scope_severity_code?e.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-xs font-bold text-white",style:{backgroundColor:Ht(o.scope_severity_code)},title:Ct[o.scope_severity_code]||"",children:o.scope_severity_code}):e.jsx("span",{className:"text-slate-400",children:"â"})}),e.jsx("td",{className:"px-3 py-2 align-top leading-snug text-slate-700",children:o.deficiency_description||"â"})]},`${o.survey_date}_${o.deficiency_prefix}${o.deficiency_tag_number}_${d}`)})})]})}),e.jsx("p",{className:"mt-3 text-[11px] italic leading-snug text-slate-400",children:"Life Safety Code (K) and Emergency Preparedness (E) citations across every survey on record. CMS scores these separately â they do not contribute to the health inspection score or the star rating, and they are not affected by the scoring window on the tab behind this dialog."})]})]})}):null}function Xi({ccn:t,facility:s}){const[a,n]=b.useState("survey_date"),[r,l]=b.useState("desc"),[o,d]=b.useState(""),[c,m]=b.useState(""),[p,i]=b.useState(""),[h,v]=b.useState(!1),[y,L]=b.useState(!1),[D,j]=b.useState(!1),[M,f]=b.useState("current"),[w,B]=b.useState(new Set),[z,_]=b.useState(null),[S,C]=b.useState(null),{data:u,isLoading:g}=ee({queryKey:["facility-deficiencies",t],queryFn:()=>nn(t),enabled:!!t}),{data:A,isLoading:x}=ee({queryKey:["facility-fire-safety",t],queryFn:()=>rn(t),enabled:!!t,staleTime:600*1e3}),{data:P}=ee({queryKey:["facility-narratives",t],queryFn:()=>ln(t),enabled:!!t,staleTime:600*1e3}),$=b.useMemo(()=>{const k=new Map;for(const q of P?.narratives||[]){const K=q.tag.replace(/^F/,"").replace(/^0+/,"")||"0";k.set(`${q.survey_date}_F${K}`,q),k.set(`${q.survey_date}_${q.tag}`,q)}return k},[P]),T=k=>{B(q=>{const K=new Set(q);return K.has(k)?K.delete(k):K.add(k),K})};if(g)return e.jsx(Te,{});const F=s?.rating_cycle_1_standard_survey_health_date?.trim()||null,R=s?.rating_cycle_1_number_of_standard_health_deficiencies,V=R!=null&&String(R).trim()!==""?parseInt(R,10):null;if(!u?.results?.length&&!F)return e.jsx(bt,{text:"No health deficiency data available for this facility."});const{summary:X,results:O}=u,G=[...new Set(O.map(k=>
5k.scope_severity_code).filter(Boolean))].sort(),J=[...new Set(O.map(k=>k.inspection_cycle).filter(Boolean))].sort(),Z=k=>k.survey_type==="standard"||k.standard_deficiency==="Y",se=k=>k.survey_type==="complaint"||k.survey_type==="infection_control"||k.complaint_deficiency==="Y"||k.infection_control_deficiency==="Y",N=[...new Set(O.filter(Z).map(k=>k.survey_date).filter(Boolean))].sort().reverse(),Y=M==="current"?2:M==="legacy3"?3:null,U=Y?new Set(N.slice(0,Y)):null,H=(()=>{const k=new Date;return k.setMonth(k.getMonth()-36),k.toISOString().slice(0,10)})(),ae=O.filter(k=>o&&k.deficiency_category!==o||c&&k.scope_severity_code!==c||p&&k.inspection_cycle!==p?!1:M==="all"?!0:Z(k)?U?U.has(k.survey_date):!0:se(k)?k.survey_date&&k.survey_date>=H:!1),I=N[0]||null,E=N[1]||null,W=(k,q)=>{if(!k||!q)return null;const K=new Date(k),Q=new Date(q);return(Q.getFullYear()-K.getFullYear())*12+(Q.getMonth()-K.getMonth())},te=k=>{if(!k.survey_date)return 0;if(Z(k))return I&&k.survey_date===I?.5:E&&k.survey_date===E?1/3:0;const q=W(k.survey_date,new Date().toISOString().slice(0,10));return q==null?0:q<=12?.5:q<=24?1/3:q<=36?1/6:0};ae.reduce((k,q)=>k+Xe(q.scope_severity_code),0);const me=ae.reduce((k,q)=>k+Xe(q.scope_severity_code)*te(q),0),Se=Math.round(me*10)/10,ve=s?.total_weighted_health_survey_score?parseFloat(s.total_weighted_health_survey_score):null,ot=ve!=null&&M==="current",Le=ot?ve:Se,He=(()=>{const k=new Map;for(const q of ae){const K=q.survey_date;if(!K)continue;k.has(K)||k.set(K,{date:K,type:q.survey_type||(Z(q)?"standard":"complaint"),weight:te(q),rows:[],rawTotal:0});const Q=k.get(K),re=Xe(q.scope_severity_code);Q.rows.push({tag:q.deficiency_tag_number,code:q.scope_severity_code,points:re}),Q.rawTotal+=re}return[...k.values()].sort((q,K)=>K.date.localeCompare(q.date))})(),Ke=[...ae].sort((k,q)=>{let K=k[a]??"",Q=q[a]??"";return K=K.toString().toLowerCase(),Q=Q.toString().toLowerCase(),K<Q?r==="asc"?-1:1:K>Q?r==="asc"?1:-1:0}),ct=k=>{a===k?l(q=>q==="asc"?"desc":"asc"):(n(k),l("asc"))},Pa=()=>{const k=["survey_date","survey_type","deficiency_tag_number","deficiency_category","deficiency_description","scope_severity_code","points","deficiency_corrected","correction_date","inspection_cycle","standard_deficiency","complaint_deficiency","infection_control_deficiency"],q=k.join(","),K=Ke.map(re=>k.map(ue=>{const be=ue==="points"?Xe(re.scope_severity_code):re[ue];return`"${String(be??"").replace(/"/g,'""')}"`}).join(",")),Q=[q,...K].join(` 6`);Ys(`deficiencies_${t}.csv`,Q)},_t=ae.reduce((k,q)=>{const K=q.scope_severity_code;return K&&(k[K]=(k[K]||0)+1),k},{}),Ra=Object.keys(_t).sort().map(k=>({code:k,count:_t[k],fill:Ht(k),label:Ct[k]||k})),Da=Object.keys(_t).sort().map(k=>({scope_severity_code:k,count:_t[k]})),ls=ae.reduce((k,q)=>{const K=q.survey_date?.slice(0,10);return K&&(k[K]||(k[K]={date:K,Citations:0,Points:0,types:new Set,tags:[]}),k[K].Citations+=1,k[K].Points+=Xe(q.scope_severity_code),q.survey_type&&k[K].types.add(q.survey_type),q.deficiency_tag_number&&k[K].tags.push(`F${q.deficiency_tag_number}${q.scope_severity_code?"("+q.scope_severity_code+")":""}`)),k},{}),Ta=Object.values(ls).sort((k,q)=>k.date.localeCompare(q.date)).map(k=>({date:k.date,Points:k.Points,Citations:k.Citations,type:[...k.types].join(", "),tags:k.tags})),jt=[],is=(k,q)=>{const K=k?.trim()?.slice(0,10),Q=q!=null&&String(q).trim()!==""?parseInt(q,10):null;K&&Q===0&&!ls[K]&&!jt.some(re=>re.date===K)&&jt.push({date:K,Points:0,Citations:0,type:"standard",tags:[],clean:!0})};is(s?.rating_cycle_1_standard_survey_health_date,s?.rating_cycle_1_number_of_standard_health_deficiencies),is(s?.rating_cycle_2_standard_health_survey_date,s?.rating_cycle_2_number_of_standard_health_deficiencies);const os=[...Ta,...jt].sort((k,q)=>k.date.localeCompare(q.date)),La=[...ae].map(k=>k.survey_date).filter(Boolean).sort().reverse()[0]||null,Oa=[{key:"survey_date",label:"Survey Date"},{key:"survey_type",label:"Type"},{key:"deficiency_tag_number",label:"Tag #"},{key:"deficiency_category",label:"Category"},{key:"deficiency_description",label:"Description"},{key:"scope_severity_code",label:"Severity"},{key:"points",label:"Points"},{key:"deficiency_corrected",label:"Status"},{key:"correction_date",label:"Corrected"},{key:"inspection_cycle",label:"Cycle"}];return e.jsxs("div",{className:"space-y-6",children:[!1,e.jsxs("div",{className:"flex items-center gap-2 text-xs print:hidden",children:[e.jsx("span",{className:"text-slate-500 font-medium",children:"CMS scoring window:"}),e.jsx("div",{className:"flex gap-1 bg-slate-100 rounded-lg p-0.5",children:[{key:"current",label:"Last 2 cycles (CMS current)",tip:"CMS July-2025 methodology: 2 most recent annual standard surveys + 36 months of complaints/IC (â30 months total)."},{key:"legacy3",label:"Last 3 cycles (legacy)",tip:"Pre-July-2025 methodology: 3 most recent standard cycles (â54 months)."},{key:"all",label:"All time",tip:"No date filter â every citation we have for this facility."}].map(k=>e.jsx("button",{onClick:()=>f(k.key),title:k.tip,className:`px-3 py-1 text-xs font-medium rounded-md transition-colors ${M===k.key?"bg-white text-slate-800 shadow-sm":"text-slate-500 hover:text-slate-700"}`,children:k.label},k.key))})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("button",{type:"button",onClick:()=>v(k=>!k),className:"text-left rounded-xl border border-slate-200 p-4 bg-white shadow-sm hover:border-sky-300 hover:bg-sky-50/30 transition-colors cursor-pointer relative",title:"Click to compare against state star-rating cut points",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide flex items-center gap-1",children:["CMS Health Inspection Score ",e.jsx(le,{text:ot?"CMS's official total_weighted_health_survey_score (last 2 cycles). Includes cycle weighting + revisit penalties.":M==="current"?"Client-side reconstruction (CMS official not in snapshot). Severity à scope per Table 1 with cycle weighting.":"Client-side reconstruction for the selected window. CMS only publishes the 'last 2 cycles' total â wider/narrower windows show our estimate."})]}),e.jsx("p",{className:`text-2xl font-bold mt-1 ${Le>=100?"text-red-600":Le>=50?"text-amber-600":"text-emerald-700"}`,children:Number(Le).toFixed(1)}),(()=>{const k=Ss(s?.state,Le),q=s?.health_inspection_rating,K=q!=null&&String(q).trim().match(/^[1-5]$/)?parseInt(q,10):null,Q=k?.stars??null,re=K!=null&&Q!=null&&K!==Q;let ue=null;re&&K<Q?s?.abuse_icon==="Y"?ue="Abuse icon cap (â¤2â )":s?.special_focus_status==="SFF"?ue="SFF / special status":ue="CMS override (IJ, SQC, or sticky rating)":re&&K>Q&&(ue="CMS sticky rating (cut-points recalibrated since last score change)");const be=ot?"CMS official":M==="current"?"client estimate":`estimate · ${M==="legacy3"?"last 3 cycles":"all time"}`;return e.jsxs("div",{className:"text-[10px] text-slate-400 mt-0.5 leading-snug",children:[e.jsxs("div",{children:[be,K!=null&&e.jsxs("span",{className:"ml-1",children:["· ",e.jsxs("span",{className:"font-semibold text-slate-700",children:["CMS: ",K,"â "]})]}),Q!=null&&e.jsxs("span",{className:"ml-1",children:["· points predict ",Q,"â in ",s.state]}),e.jsx("span",{className:"ml-1 text-sky-500",children:h?"hide details":"show cycle detail"})]}),re&&ue&&e.jsx("div",{className:"text-slate-500 italic mt-0.5",title:"CMS may apply rating caps (abuse-icon, IJ, SQC, SFF) and uses 'sticky' cut-points held constant until the facility's points change. See CMS Five-Star Technical Users' Guide April 2026, pp. 9-10.",children:ue})]})})()]}),e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 bg-white shadow-sm",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:["Total Citations ",e.jsx(le,{text:"Citation count within the selected CMS scoring window + current filters."})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-slate-800 tabular-nums",children:ae.length}),ae.length!==X.total_citations&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5",children:["of ",X.total_citations," total all-time"]})]}),(()=>
6{const k=La??X.most_recent_survey??null,q=[F,k].filter(Boolean).sort().reverse()[0]??null,K=!!q&&q===F&&V===0,Q=!K&&q===X.most_recent_survey&&X.most_recent_survey_kinds?.length>0?X.most_recent_survey_kinds:["standard"],re=be=>`https://www.medicare.gov/care-compare/inspections/pdf/nursing-home/${t}/health/${be==="complaint"?"complaint-inspection":"health-inspection"}?date=${q}`,ue=be=>be==="complaint"?"View Complaint Report":Q.length>1?"View Standard Report":"View Full CMS Report";return e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 bg-white shadow-sm",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:["Most Recent Survey ",e.jsx(le,{text:"Latest standard health survey (CMS cycle-1 date) or complaint inspection, whichever is newer â including deficiency-free surveys, which carry no citations."})]}),e.jsx("p",{className:"text-lg font-bold mt-1 text-slate-800 tabular-nums",children:q??"â"}),K&&e.jsxs("span",{className:"inline-flex items-center gap-1 mt-1 px-1.5 py-0.5 rounded text-[10px] font-semibold bg-emerald-100 text-emerald-700",children:[e.jsx(us,{size:11})," Deficiency-free standard survey"]}),q&&e.jsx("div",{className:"flex flex-col gap-0.5 mt-1.5",children:Q.map(be=>e.jsx("a",{href:re(be),target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-xs text-sky-600 hover:text-sky-800 font-medium",children:ue(be)},be))})]})})(),(()=>{const k=A?.summary,q=e.jsxs("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide flex items-center gap-1",children:["Fire Safety Tags ",e.jsx(le,{text:"Life Safety Code (K) and Emergency Preparedness (E) citations across every survey on record â sprinklers, generators, egress, smoke doors. CMS scores these separately: they do NOT affect the health inspection score or star rating, and they are not filtered by the scoring window above."})]});if(x||!k)return e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 bg-white shadow-sm",children:[q,e.jsx("p",{className:"text-2xl font-bold mt-1 text-slate-300 tabular-nums",children:"â"})]});const K=k.national_median!=null&&k.total_citations>k.national_median,Q=e.jsxs(e.Fragment,{children:[q,e.jsx("p",{className:`text-2xl font-bold mt-1 tabular-nums ${K?"text-amber-600":"text-slate-800"}`,children:k.total_citations}),e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5 leading-snug",children:[k.life_safety_count," life safety · ",k.emergency_prep_count," emergency prep"]}),e.jsxs("p",{className:"text-[10px] text-slate-400 leading-snug",children:["all surveys on record",k.national_median!=null&&e.jsxs(e.Fragment,{children:[" · national median ",e.jsx("span",{className:"font-semibold text-slate-700 tabular-nums",children:k.national_median})]}),k.total_citations>0&&e.jsx("span",{className:"ml-1 text-sky-500",children:"view citations"})]})]});return k.total_citations===0?e.jsx("div",{className:"rounded-xl border border-slate-200 p-4 bg-white shadow-sm",children:Q}):e.jsx("button",{type:"button",onClick:()=>j(!0),"aria-haspopup":"dialog",className:"text-left rounded-xl border border-slate-200 p-4 bg-white shadow-sm hover:border-sky-300 hover:bg-sky-50/30 transition-colors cursor-pointer",title:"Click to see every fire safety citation on record",children:Q})})()]}),e.jsx(Ji,{open:D,onClose:()=>j(!1),rows:A?.results??[],summary:A?.summary,providerName:s?.provider_name}),h&&s?.state&&Qt[s.state]&&(()=>{const k=Qt[s.state],q=Ss(s.state,Le),K=[5,4,3,2,1].map(Q=>({stars:Q,range:k[String(Q)]}));return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-lg shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("h4",{className:"text-xs font-semibold text-slate-700 uppercase tracking-wide",children:[s.state," Health-Inspection Star Bands"]}),e.jsx("button",{onClick:()=>v(!1),className:"text-xs text-slate-400 hover:text-slate-600",children:"Close"})]}),e.jsxs("table",{className:"w-full text-xs border border-slate-200 rounded overflow-hidden",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-slate-50 text-slate-500",children:[e.jsx("th",{scope:"col",className:"text-left font-semibold uppercase tracking-wide px-3 py-1.5 border-b border-slate-200",children:"Rating"}),e.jsx("th",{scope:"col",className:"text-right font-semibold uppercase tracking-wide px-3 py-1.5 border-b border-slate-200",children:"Weighted Point Range"})]})}),e.jsx("tbody",{children:K.map(Q=>{const re=q&&q.stars===Q.stars;return e.jsxs("tr",{className:re?"bg-sky-50":"",children:[e.jsxs("td",{className:`px-3 py-1.5 border-b border-slate-100 ${re?"font-semibold text-slate-800":"text-slate-600"}`,children:[Q.stars,"â
",re&&e.jsx("span",{className:"ml-2 text-[10px] font-medium text-sky-700",children:"this facility"})]}),e.jsx("td",{className:`px-3 py-1.5 border-b border-slate-100 text-right tabular-nums ${re?"font-semibold text-slate-800":"text-slate-500"}`,children:Q.range})]},Q.stars)})})]}),q?e.jsxs("p",{className:"text-xs text-slate-600 mt-3",children:[e.jsxs("span",{className:"font-semibold text-slate-800",children:[Le," pts"]})," = ",e.jsxs("span",{className:"font-semibold text-slate-800",children:[q.stars,"â
"]}),q.to_next_higher!=null&&q.to_next_higher>0&&e.jsxs("span",{className:"text-slate-500",children:[" · ",q.to_next_higher.toFixed(1)," pts to ",q.stars+1,"â
"]}),q.to_next_lower!=null&&q.to_next_lower>0&&e.jsxs("span",{className:"text-slate-500",children:[" · ",q.to_next_lower.toFixed(1)," pt buffer to ",q.stars-1,"â
"]})]}):e.jsx("p",{className:"text-xs text-slate-500 italic mt-3",children:"No band match for these points."}),e.jsxs("button",{onClick:()=>L(Q=>!Q),className:"text-[11px] text-sky-600 hover:text-sky-800 mt-2",children:[y?"Hide":"Show"," cycle breakdown + reconciliation"]}),y&&e.jsxs("div",{className:"mt-3 space-y-3 border-t border-slate-100 pt-3",children:[(s?.rating_cycle_1_total_health_score||s?.rating_cycle_23_total_health_score)&&e.jsxs("div",{className:"text-[11px] text-slate-600 space-y-1",children:[e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"Cycle 1"})," (",s.rating_cycle_1_standard_survey_health_date||"?","):"," ",s.rating_cycle_1_number_of_standard_health_deficiencies||0," std + ",s.rating_cycle_1_number_of_complaint_health_deficiencies||0," complaint, def score ",s.rating_cycle_1_health_deficiency_score||0,", revisit +",s.rating_cycle_1_health_revisit_score||0," ="," ",e.jsxs("span",{className:"font-mono font-semibold text-slate-800",children:[s.rating_cycle_1_total_health_score||"?"," à 1/2"]})]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-700",children:"Cycle 2+3"})," (std ",s.rating_cycle_2_standard_health_survey_date||"?","):"," ",s.rating_cycle_2_number_of_standard_health_deficiencies||0," std + ",s.rating_cycle_23_number_of_complaint_health_deficiencies||0," complaint, def score ",s.rating_cycle_23_health_deficiency_score||0,", revisit +",s.rating_cycle_23_health_revisit_score||0," ="," ",e.jsxs("span",{className:"font-mono font-semibold text-slate-800",children:[s.rating_cycle_23_total_health_score||"?"," à 1/3"]})]}),e.jsxs("p",{className:"font-semibold text-slate-700 pt-1 border-t border-slate-100",children:["CMS total_weighted_health_survey_score = ",e.jsx("span",{className:"font-mono text-slate-800",children:s.total_weighted_health_survey_score||"?"})]})]}),He.length>0&&e.jsxs("div",{className:"space-y-1 text-[11px]",children:[e.jsx("p",{className:"font-semibold text-slate-700",children:"Per-survey contribution (from in-window citations)"}),He.map(Q=>e.jsxs("p",{className:"font-mono text-slate-600",children:[Q.date," ",e.jsxs("span",{className:"text-slate-400",children:["(",Q.type,")"]}),": ",Q.rawTotal," raw à ",Q.weight===.5?"0.5":Q.weight===1/3?"0.333":Q.weight===1/6?"0.167":Q.weight.toFixed(3)," = ",e.jsx("span",{className:"font-semibold text-slate-800",children:(Q.rawTotal*Q.weight).toFixed(1)})," pts",e.jsxs("span",{className:"ml-2 text-slate-400",children:["[",Q.rows.map(re=>"F"+re.tag+re.code).join(", "),"]"]})]},Q.date))]}),e.jsx("p",{className:"text-[10px] text-slate-400 italic",children:"Cycle weights: standard Ã1/2 (most recent) / Ã1/3 (prior). Complaint/IC: Ã1/2 (last 12mo) / Ã1/3 (12â24mo) / Ã1/6 (24â36mo). Bands via CMS hicp-9999."})]})]})})(),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-5",children:[Ra.length>0&&e.jsx(Oi,{title:"CMS Scope & Severity Grid",sub:"Citations by harm severity (rows) à scope (columns)",rightHeader:e.jsx(Vr,{}),children:()=>e.jsx("div",{className:"px-1 pb-1",children:e.jsx(Wr,{data:Da,size:"md",showPercent:!0})})}),os.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5 h-full flex flex-col",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700",children:"Survey Timeline"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["CMS Inspection Points per survey (raw, before cycle weighting). Hover for citations + F-tags.",jt.length>0&&e.jsx("span",{className:"text-emerald-600",children:" Green dot = deficiency-free survey."})]})]}),e.jsx("div",{className:"flex-1 min-h-[260px] mt-3",children:e.jsx(je,{width:"100%",height:"100%",children:e.jsxs(it,{data:os,children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:10},angle:-30,textAnchor:"end",height:50}),e.jsx(xe,{tick:{fontSize:11},allowDecimals:!1,domain:[0,k=>Math.max(k||0,4)]}),e.jsx(ce,{content:({active:k,payload:q})=>
6{if(!k||!q?.length)return null;const K=q[0].payload;return e.jsxs("div",{className:"bg-slate-800 text-slate-100 rounded-lg shadow-lg p-3 text-xs max-w-xs",children:[e.jsxs("p",{className:"font-semibold mb-1",children:[K.date,K.type?` (${K.type})`:""]}),K.clean?e.jsx("p",{className:"text-emerald-300 font-semibold",children:"0 pts · deficiency-free standard survey"}):e.jsxs("p",{className:"text-amber-300 font-semibold",children:[K.Points," pts ",e.jsxs("span",{className:"text-slate-300 font-normal",children:["·"," ",K.Citations," citation",K.Citations!==1?"s":""]})]}),K.tags?.length>0&&e.jsxs("p",{className:"mt-1.5 text-slate-300 leading-relaxed",children:[e.jsx("span",{className:"text-slate-400",children:"Tags: "}),K.tags.join(", ")]})]})}}),e.jsx(_e,{dataKey:"Points",fill:"#0ea5e9",radius:[4,4,0,0],shape:k=>{const{x:q,y:K,width:Q,height:re,payload:ue}=k;return ue?.clean?e.jsx("circle",{cx:q+Q/2,cy:K,r:4.5,fill:"#10b981",stroke:"#fff",strokeWidth:1}):e.jsx("rect",{x:q,y:K,width:Q,height:re,rx:4,fill:"#0ea5e9"})}})]})})})]})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 border-b border-slate-200 bg-slate-50",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-slate-500",children:[Ke.length," of ",O.length," citations"]}),e.jsxs("select",{value:o,onChange:k=>d(k.target.value),className:"text-xs border border-slate-300 rounded px-2 py-1 max-w-[200px] focus:outline-none focus:ring-1 focus:ring-sky-500",title:"Service line â filter to deficiencies in a vendor domain (dietary, environmental/housekeeping, pharmacy, etc.).",children:[e.jsx("option",{value:"",children:"All service lines"}),Qr.map(k=>e.jsx("option",{value:k.value,children:k.label},k.value))]}),e.jsxs("select",{value:c,onChange:k=>m(k.target.value),className:"text-xs border border-slate-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-sky-500",children:[e.jsx("option",{value:"",children:"All Severities"}),G.map(k=>e.jsxs("option",{value:k,children:[k," â ",Ct[k]?.split("·")[0]?.trim()||k]},k))]}),J.length>1&&e.jsxs("select",{value:p,onChange:k=>i(k.target.value),className:"text-xs border border-slate-300 rounded px-2 py-1 focus:outline-none focus:ring-1 focus:ring-sky-500",children:[e.jsx("option",{value:"",children:"All Cycles"}),J.map(k=>e.jsxs("option",{value:k,children:["Cycle ",k]},k))]})]}),e.jsxs("button",{onClick:Pa,className:"flex items-center gap-1 text-xs text-slate-500 hover:text-sky-600 transition-colors",children:[e.jsx(Ue,{size:12})," Export CSV"]})]}),Ke.length===0?e.jsxs("div",{className:"px-4 py-10 text-center",children:[e.jsx(us,{size:20,className:"text-emerald-500 mx-auto mb-2"}),e.jsxs("p",{className:"text-sm text-slate-500",children:["No health-inspection citations on record for this facility",M!=="all"?" in the selected window":"","."]})]}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsx("tr",{children:Oa.map(k=>e.jsxs("th",{scope:"col",onClick:()=>ct(k.key),className:"px-3 py-2 text-xs font-semibold text-slate-500 uppercase tracking-wide cursor-pointer hover:text-slate-800 select-none whitespace-nowrap text-left",children:[k.label,a===k.key&&e.jsx("span",{className:"ml-1 text-sky-500",children:r==="asc"?"â²":"â¼"})]},k.key))})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:Ke.map((k,q)=>{const K=`${k.survey_date}_${k.deficiency_prefix||"F"}${String(k.deficiency_tag_number).replace(/^0+/,"")||"0"}`,Q=$.get(K),re=`${k.survey_date}_${k.deficiency_tag_number}_${q}`,ue=w.has(re);return e.jsxs(b.Fragment,{children:[e.jsxs("tr",{className:`hover:bg-slate-50 ${Q?"cursor-pointer":""}`,onClick:Q?()=>T(re):void 0,children:[e.jsx(ne,{mono:!0,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[Q&&e.jsx("span",{className:`text-sky-500 transition-transform ${ue?"rotate-90":""}`,children:"â¸"}),k.survey_date]})}),e.jsx(ne,{children:e.jsx("span",{className:"text-xs",children:k.survey_type??"â"})}),e.jsx(ne,{children:k.deficiency_tag_number?e.jsxs(lt,{to:`/deficiencies?tab=library&ftag=${k.deficiency_prefix||"F"}${String(k.deficiency_tag_number).replace(/^0+/,"")||"0"}`,className:"font-mono text-xs text-sky-600 hover:text-sky-800 hover:underline",title:"View F-tag guidance in Library",target:"_blank",rel:"noopener noreferrer",onClick:be=>be.stopPropagation(),children:[k.deficiency_prefix,k.deficiency_tag_number]}):e.jsx("span",{className:"font-mono text-xs",children:"â"})}),e.jsx(ne,{children:e.jsx("span",{className:"text-xs",children:k.deficiency_category??"â"})}),e.jsx(ne,{children:Q?.summary?e.jsxs("div",{children:[e.jsx("span",{className:"text-xs leading-snug font-medium text-slate-800",children:Q.summary}),e.jsx("span",{className:"text-[10px] text-slate-400 ml-2",children:"(click to expand)"})]}):e.jsx("span",{className:"text-xs leading-snug",children:k.deficiency_description??"â"})}),e.jsx(ne,{children:k.scope_severity_code?e.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-xs font-bold text-white",style:{backgroundColor:Ht(k.scope_severity_code)},title:Ct[k.scope_severity_code]||"",children:k.scope_severity_code}):"â"}),e.jsx(ne,{children:e.jsx("span",{className:"text-xs font-semibold text-amber-700",title:"CMS Five-Star Table 1 â severity à scope weight",children:Xe(k.scope_severity_code)||"0"})}),e.jsx(ne,{children:e.jsx("span",{className:"text-xs",children:k.deficiency_corrected??"â"})}),e.jsx(ne,{mono:!0,children:k.correction_date??"â"}),e.jsx(ne,{children:e.jsx("span",{className:"text-xs",children:k.inspection_cycle??"â"})})]}),ue&&Q&&e.jsx("tr",{className:"bg-slate-50",children:e.jsx("td",{colSpan:10,className:"px-6 py-4 border-l-4 border-sky-400",children:e.jsx(Yr,{n:Q})})})]},re)})})]})})]})]})}function Et({title:t,value:s,sub:a,accent:n=!1,onSubClick:r,subTitle:l}){return e.jsxs("div",{className:`rounded-xl border p-4 bg-white ${n?"border-sky-200":"border-slate-200"}`,children:[e.jsx("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:t}),e.jsx("p",{className:`text-2xl font-bold mt-1 ${n?"text-sky-600":"text-slate-800"}`,children:s??"â"}),a&&(r?e.jsxs("button",{type:"button",onClick:r,className:"text-xs text-slate-400 hover:text-slate-700 hover:underline mt-0.5 text-left",title:l||"See all in state",children:[a," â"]}):e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:a}))]})}const Ze={high:"bg-red-500",medium:"bg-amber-500",low:"bg-blue-500"},Ms={high:Xt,medium:ma,low:Ye},It={staffing:"Staffing",compliance:"Compliance",market:"Market",financial:"Financial"},$s={high:{icon:Xt,label:"High",badge:"bg-negative-soft text-negative",bar:"bg-negative"},medium:{icon:ma,label:"Med",badge:"bg-warning-soft text-warning",bar:"bg-warning"},low:{icon:Ye,label:"Low",badge:"bg-secondary text-secondary-foreground",bar:"bg-primary"}};function ja({ccn:t,autoShowTop:s=!1,variant:a="classic"}){const[n,r]=b.useState(!1),[l,o]=b.useState(null),{data:d}=ee({queryKey:["top-priorities",t],queryFn:()=>on(t),enabled:!!t,staleTime:300*1e3});if(!d||!Array.isArray(d.priorities)||d.priorities.length===0)return null;const c=d.priorities.reduce((h,v)=>(h[v.severity]=(h[v.severity]||0)+1,h),{}),m=["high","medium","low"].filter(h=>c[h]).map(h=>`${c[h]} ${h}`).join(" · "),p=d.priorities,i=s&&p.length?p[0].severity==="high"?p.slice(0,1):p.slice(0,2):[];if(a==="terminal"){const h=n?p:i.length?i:p.slice(0,1),v=p.length-h.length;return e.jsxs("section",{children:[e.jsxs("div",{className:"mb-5 flex items-end justify-between gap-4 border-b border-border pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"mb-1.5 font-mono text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground",children:"Signal Engine"}),e.jsx("h2",{className:"text-xl font-bold tracking-tight text-foreground",children:"Priority Insights"})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-1.5",children:[e.jsxs("span",{className:"inline-flex items-center rounded-md border border-border bg-secondary px-1.5 py-0.5 font-mono text-[10px] font-medium text-secondary-foreground",children:[d.priorities.length," ",d.priorities.length===1?"item":"items"]}),c.high&&e.jsxs("span",{className:"inline-flex items-center rounded-md border border-negative/25 bg-negative-soft px-1.5 py-0.5 font-mono text-[10px] font-medium text-negative",children:[c.high," high"]}),c.medium&&e.jsxs("span",{className:"inline-flex items-center rounded-md border border-warning/30 bg-warning-soft px-1.5 py-0.5 font-mono text-[10px] font-medium text-warning",children:[c.medium," med"]}),c.low&&e.jsxs("span",{className:"inline-flex items-center rounded-md border border-border bg-secondary px-1.5 py-0.5 font-mono text-[10px] font-medium text-secondary-foreground",children:[c.low," low"]})]})]}),e.jsx("div",{className:"flex flex-col gap-3",children:h.map(y=>{const L=$s[y.severity]||$s.low,D=L.icon;return e.jsx("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:`w-1 shrink-0 ${L.bar}`}),e.jsxs("div",{className:"min-w-0 flex-1 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 font-mono text-[10px] font-semibold uppercase tracking-wide ${L.badge}`,children:[e.jsx(D,{className:"size-3"})," ",L.label]}),e.jsx("span",{className:"font-mono text-[10px] font-semibold uppercase tracking-wide text-muted-foreground",children:It[
6y.category]||y.category})]}),y.metric&&e.jsx("span",{className:"inline-flex shrink-0 items-center rounded-md bg-positive-soft px-1.5 py-0.5 font-mono text-[11px] font-medium text-positive",children:y.metric})]}),e.jsx("div",{className:"mt-2 text-[15px] font-semibold leading-snug text-foreground",children:y.headline}),y.detail&&e.jsx("p",{className:"mt-1 text-[13px] leading-relaxed text-muted-foreground",children:y.detail}),y.action&&e.jsxs("div",{className:"mt-3 flex items-start gap-2 rounded-lg border border-border bg-secondary/50 p-3",children:[e.jsx(ol,{className:"mt-0.5 size-4 shrink-0 text-muted-foreground"}),e.jsxs("p",{className:"text-[13px] leading-relaxed text-foreground",children:[e.jsx("span",{className:"font-semibold",children:"Action."})," ",y.action]})]})]})]})},y.rank)})}),(v>0||n)&&p.length>(i.length||1)&&e.jsxs("button",{type:"button",onClick:()=>r(!n),className:"mt-3 inline-flex items-center gap-1 font-mono text-[11px] font-medium text-primary hover:underline focus:outline-none",children:[n?"Show less":`Show ${v} more ${v===1?"item":"items"}`,n?e.jsx(Ae,{className:"size-3.5"}):e.jsx(ye,{className:"size-3.5"})]})]})}return e.jsxs("div",{className:"col-span-2 md:col-span-4 rounded-xl border border-slate-200 bg-white shadow-sm",children:[e.jsxs("button",{type:"button",onClick:()=>r(!n),className:"flex w-full items-center gap-3 px-5 py-3 text-left hover:bg-slate-50 focus:outline-none rounded-xl",children:[e.jsx("span",{className:"text-sm font-semibold text-slate-900",children:"Priority insights"}),e.jsxs("span",{className:"text-xs text-slate-500",children:["· ",d.priorities.length," ",d.priorities.length===1?"item":"items"]}),m&&e.jsxs("span",{className:"text-xs text-slate-400",children:["· ",m]}),e.jsxs("span",{className:"ml-auto flex items-center gap-2",children:[e.jsx("span",{className:"flex items-center gap-1",children:d.priorities.map(h=>e.jsx("span",{className:`h-2 w-2 rounded-full ${Ze[h.severity]||Ze.low}`},h.rank))}),n?e.jsx(Ae,{className:"h-4 w-4 text-slate-400"}):e.jsx(ye,{className:"h-4 w-4 text-slate-400"})]})]}),i.length>0&&!n&&e.jsxs("ul",{className:"border-t border-slate-100 divide-y divide-slate-100",children:[i.map(h=>{const v=Ms[h.severity]||Ye;return e.jsx("li",{className:"px-5 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:`h-2 w-2 mt-1.5 rounded-full flex-shrink-0 ${Ze[h.severity]||Ze.low}`}),e.jsx(v,{className:"h-3.5 w-3.5 mt-1 text-slate-400 flex-shrink-0"}),e.jsx("span",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide w-20 flex-shrink-0 mt-1",children:It[h.category]||h.category}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-slate-800",children:h.headline}),h.metric&&e.jsx("span",{className:"font-mono text-xs font-semibold text-slate-600 flex-shrink-0",children:h.metric})]}),h.detail&&e.jsx("p",{className:"mt-1 text-xs text-slate-600",children:h.detail}),h.action&&e.jsxs("div",{className:"mt-2 rounded bg-slate-50 px-3 py-2 text-xs text-slate-600",children:[e.jsx("span",{className:"font-semibold text-slate-900",children:"Action: "}),h.action]})]})]})},h.rank)}),p.length>i.length&&e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>r(!0),className:"flex w-full items-center gap-1 px-5 py-2 text-left text-xs font-semibold text-sky-600 hover:bg-slate-50 hover:text-sky-800 focus:outline-none",children:["Show ",p.length-i.length," more ",p.length-i.length===1?"item":"items",e.jsx(ye,{className:"h-3.5 w-3.5"})]})})]}),n&&e.jsx("ul",{className:"border-t border-slate-100 divide-y divide-slate-100",children:d.priorities.map(h=>{const v=Ms[h.severity]||Ye,y=l===h.rank;return e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>o(y?null:h.rank),className:"flex w-full items-center gap-3 px-5 py-2 text-left hover:bg-slate-50 focus:outline-none",children:[e.jsx("span",{className:`h-2 w-2 rounded-full flex-shrink-0 ${Ze[h.severity]||Ze.low}`}),e.jsx(v,{className:"h-3.5 w-3.5 text-slate-400 flex-shrink-0"}),e.jsx("span",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide w-20 flex-shrink-0",children:It[h.category]||h.category}),e.jsx("span",{className:"flex-1 text-sm text-slate-800 truncate",children:h.headline}),h.metric&&e.jsx("span",{className:"font-mono text-xs font-semibold text-slate-600 flex-shrink-0",children:h.metric}),y?e.jsx(Ae,{className:"h-4 w-4 text-slate-400"}):e.jsx(ye,{className:"h-4 w-4 text-slate-400"})]}),y&&e.jsxs("div",{className:"px-5 pb-3 pl-16 text-xs text-slate-600",children:[h.detail&&e.jsx("p",{className:"mb-2",children:h.detail}),h.action&&e.jsxs("div",{className:"rounded bg-slate-50 px-3 py-2",children:[e.jsx("span",{className:"font-semibold text-slate-900",children:"Action: "}),h.action]})]})]},h.rank)})})]})}const Fs=[["quality_component","Clinical Quality"],["staffing_component","Staffing & Leadership"],["stability_component","Trend & Momentum"],["regulatory_component","Market Position"],["financial_component","Financial Health"]];function xt(t){if(!t)return"";const[s,a]=t.split("-");return`${["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][parseInt(a)-1]} ${parseInt(t.slice(8))}`}function As(t,s){if(t==null)return e.jsx("span",{className:"text-slate-400",children:"â"});if(s==null)return e.jsx("span",{className:"text-slate-700 font-medium",children:t.toFixed(1)});const a=t-s;if(Math.abs(a)<.05)return e.jsx("span",{className:"text-slate-700 font-medium",children:t.toFixed(1)});const n=Math.abs(a)<.5?"text-slate-400":a>0?"text-emerald-600":"text-red-600",r=a>0?"+":"";return e.jsxs("span",{className:"text-slate-700 font-medium whitespace-nowrap",children:[t.toFixed(1)," ",e.jsxs("span",{className:`text-[10px] ${n}`,children:[r,a.toFixed(1)]})]})}function va({ccn:t,facilityName:s,onClose:a}){const{data:n,isLoading:r}=ee({queryKey:["insight-score-history",t],queryFn:()=>cn(t),staleTime:36e5}),l=n?.points||[],o=l[l.length-1],d=l[0],c=o&&d?o.score-d.score:0,m=l.map(f=>f.score).filter(f=>f!=null),p=m.length?Math.min(...m):0,i=m.length?Math.max(...m):100,h=Math.max(3,Math.min(8,(i-p)*.3)),v=Math.max(0,Math.floor(p-h)),y=Math.min(100,Math.ceil(i+h)),L=v<50&&y>50,D=De(a),[j,M]=b.useState(!1);return e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-3 md:p-6",onClick:a,children:e.jsxs("div",{ref:D,role:"dialog","aria-modal":"true","aria-labelledby":"insight-score-history-title",className:"bg-white rounded-lg shadow-lg w-full max-w-3xl max-h-[90vh] overflow-y-auto",onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-slate-200 flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"insight-score-history-title",className:"text-base font-semibold text-slate-800",children:"SNF InsightScore â Trend"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:s||t})]}),e.jsx("button",{onClick:a,"aria-label":"Close",className:"p-1.5 rounded-lg hover:bg-slate-100 text-slate-500",title:"Close",children:e.jsx(Me,{size:18})})]}),r&&e.jsxs("div",{className:"flex items-center justify-center py-16 text-slate-400 text-sm gap-2",children:[e.jsx(ge,{size:16,className:"animate-spin"})," Loading historyâ¦"]}),!r&&l.length===0&&e.jsx("div",{className:"text-center text-slate-400 py-12 text-sm",children:"No history yet for this facility â history begins with the first CMS snapshot after backfill."}),!r&&l.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-5 py-3 border-b border-slate-100 grid grid-cols-3 gap-4 text-center bg-slate-50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"First"}),e.jsxs("p",{className:"text-sm font-bold text-slate-700 mt-0.5",children:[d?.score?.toFixed(1)," ",e.jsx("span",{className:"text-[10px] font-normal text-slate-400",children:xt(d?.snapshot_date)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"Latest"}),e.jsxs("p",{className:"text-sm font-bold text-slate-700 mt-0.5",children:[o?.score?.toFixed(1)," ",e.jsx("span",{className:"text-[10px] font-normal text-slate-400",children:xt(o?.snapshot_date)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:"YTD Change"}),e.jsxs("p",{className:`text-sm font-bold mt-0.5 ${Math.abs(c)<.5?"text-slate-600":c>0?"text-emerald-600":"text-red-600"}`,children:[c>0?"+":"",c.toFixed(1)]})]})]}),e.jsxs("div",{className:"px-5 py-4",children:[e.jsx("div",{style:{width:"100%",height:250},children:e.jsx(je,{children:e.jsxs($e,{data:l,margin:{top:8,right:12,bottom:6,left:-8},children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"snapshot_date",tick:{fontSize:10,fill:"#64748b"},tickFormatter:xt}),e.jsx(xe,{domain:[v,y],tick:{fontSize:10,fill:"#64748b"},allowDecimals:!1}),e.jsx(ce,{formatter:f=>[(+f).toFixed(1),"Score"],labelFormatter:xt,contentStyle:{fontSize:12,borderRadius:8,border:"1px solid #e2e8f0"}}),L&&e.jsx(ss,{y:50,stroke:"#cbd5e1",strokeDasharray:"3 3",label:{value:"Median",fontSize:9,fill:"#94a3b8",position:"insideRight"}}),e.jsx(oe,{type:"monotone",dataKey:"score",stroke:"#0284c7",strokeWidth:2.5,dot:{r:4,fill:"#0284c7",strokeWidth:0},activeDot:{r:6}})]})})}),e.jsx("p",{className:"text-[10px] text-slate-400 mt-2 leading-snug",children:"One point per monthly CMS snapshot. A new point is added each month when the latest CMS data is loaded. Y-axis auto-scales to the visible range so small month-over-month changes are easier to read."})]}),e.jsxs("div",{className:"px-5 pb-5",children:[e.jsxs("button",{type:"button",onClick:()=>M(f=>!f),"aria-expanded":j,className:"flex items-center gap-1 text-[10px] uppercase tracking-wide text-slate-500 font-semibold mb-2 hover:text-slate-700 transition-colors",children:[j?e.jsx(Ae,{size:12}):e.jsx(ye,{size:12}),"Component breakdown"]}),j&&e.jsx("div",{className:"overflow-x-auto border border-slate-200 rounded-lg",children:e.jsxs("table",{className:"w-full text-xs tabular-nums",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500",children:"Snapshot"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500",children:"Score"}),Fs.map(([,f])=>e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500
6whitespace-nowrap",children:f},f))]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:l.map((f,w)=>{const B=w>0?l[w-1]:null;return e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-3 py-2 text-slate-700 font-medium",children:xt(f.snapshot_date)}),e.jsx("td",{className:"px-3 py-2 text-left",children:As(f.score,B?.score)}),Fs.map(([z])=>e.jsx("td",{className:"px-3 py-2 text-left",children:As(f[z],B?.[z])},z))]},f.snapshot_date)})})]})})]})]})]})})}const Zi={total_pop:{label:"Total Population",fmt:t=>t!=null?Math.round(t).toLocaleString():"â"},pct_65_plus:{label:"Pop. 65+ (%)",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},pop_85_plus:{label:"Pop. 85+",fmt:t=>t!=null?Math.round(t).toLocaleString():"â"},median_hhi:{label:"Median HHI",fmt:t=>t!=null?"$"+Math.round(t).toLocaleString():"â"},median_home_value:{label:"Median Home Value",fmt:t=>t!=null?"$"+Math.round(t).toLocaleString():"â"},poverty_rate:{label:"Poverty Rate",fmt:t=>t!=null?t.toFixed(1)+"%":"â"}};function Na({ccn:t,metric:s,facilityName:a,onClose:n}){const{data:r,isLoading:l}=ee({queryKey:["county-demo-rank",t,s],queryFn:()=>dn(t,s),staleTime:36e5}),o=Zi[s]||{label:s,fmt:p=>String(p??"â")},d=r?.counties||[],c=d.find(p=>p.is_subject),m=De(n);return e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-3 md:p-6",onClick:n,children:e.jsxs("div",{ref:m,role:"dialog","aria-modal":"true","aria-labelledby":"county-demo-rank-title",className:"bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:p=>p.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-slate-200 flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsxs("div",{children:[e.jsxs("h2",{id:"county-demo-rank-title",className:"text-base font-semibold text-slate-800",children:[o.label," â county rank"]}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[a||t,r?.state?` · ${r.state}`:"",c?` · #${c.rank} of ${d.length}`:"",r?.lower_is_better&&e.jsx("span",{className:"ml-2 text-[10px] italic text-slate-400",children:"(lower is better)"})]})]}),e.jsx("button",{onClick:n,"aria-label":"Close",className:"p-1.5 rounded-lg hover:bg-slate-100 text-slate-500",title:"Close",children:e.jsx(Me,{size:18})})]}),l&&e.jsxs("div",{className:"flex items-center justify-center py-16 text-slate-400 text-sm gap-2",children:[e.jsx(ge,{size:16,className:"animate-spin"})," Loadingâ¦"]}),!l&&d.length===0&&e.jsx("div",{className:"text-center text-slate-400 py-12 text-sm",children:"No county data available for this state."}),!l&&d.length>0&&e.jsx("div",{className:"px-5 py-4",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-50 border-y border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500 w-12",children:"Rank"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500",children:"County"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-slate-500",children:o.label})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:d.map(p=>e.jsxs("tr",{className:p.is_subject?"bg-sky-50":"hover:bg-slate-50",ref:i=>{p.is_subject&&i&&typeof i.scrollIntoView=="function"&&setTimeout(()=>i.scrollIntoView({block:"center",behavior:"auto"}),50)},children:[e.jsxs("td",{className:`px-3 py-2 font-medium ${p.is_subject?"text-sky-700":"text-slate-500"}`,children:["#",p.rank]}),e.jsxs("td",{className:`px-3 py-2 ${p.is_subject?"font-semibold text-sky-800":"text-slate-700"}`,children:[p.county_name,p.is_subject&&e.jsx("span",{className:"ml-1.5 text-[9px] font-bold text-white bg-sky-600 px-1.5 py-0.5 rounded uppercase tracking-wide align-middle",children:"This facility"})]}),e.jsx("td",{className:`px-3 py-2 text-right font-mono ${p.is_subject?"font-bold text-sky-800":"text-slate-700"}`,children:o.fmt(p.value)})]},p.fips))})]})})]})})}const eo={ma_penetration:{label:"MA Penetration",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},ma_enrolled:{label:"MA Enrolled",fmt:t=>
6t!=null?Math.round(t).toLocaleString():"â"},top_plan_share:{label:"Top Plan Share",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},medicare_growth:{label:"Medicare Pop. Growth (YoY)",fmt:t=>t!=null?(t>0?"+":"")+t.toFixed(1)+"%":"â"}};function wa({ccn:t,metric:s,facilityName:a,reportDate:n,onClose:r}){const{data:l,isLoading:o}=ee({queryKey:["ma-county-rank",t,s],queryFn:()=>xn(t,s),staleTime:36e5}),d=eo[s]||{label:s,fmt:i=>String(i??"â")},c=l?.counties||[],m=c.find(i=>i.is_subject),p=De(r);return e.jsx("div",{className:"fixed inset-0 z-50 bg-black/60 flex items-center justify-center p-3 md:p-6",onClick:r,children:e.jsxs("div",{ref:p,role:"dialog","aria-modal":"true","aria-labelledby":"ma-county-rank-title",className:"bg-white rounded-lg shadow-lg w-full max-w-2xl max-h-[90vh] overflow-y-auto",onClick:i=>i.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-slate-200 flex items-center justify-between sticky top-0 bg-white z-10",children:[e.jsxs("div",{children:[e.jsxs("h2",{id:"ma-county-rank-title",className:"text-base font-semibold text-slate-800",children:[d.label," â county rank"]}),e.jsxs("p",{className:"text-xs text-slate-500 mt-0.5",children:[a||t,l?.state?` · ${l.state}`:"",m?` · #${m.rank} of ${c.length}`:"",n&&e.jsxs("span",{className:"ml-2 text-[10px] italic text-slate-400",children:["(as of ",n,")"]})]})]}),e.jsx("button",{onClick:r,"aria-label":"Close",className:"p-1.5 rounded-lg hover:bg-slate-100 text-slate-500",title:"Close",children:e.jsx(Me,{size:18})})]}),o&&e.jsxs("div",{className:"flex items-center justify-center py-16 text-slate-400 text-sm gap-2",children:[e.jsx(ge,{size:16,className:"animate-spin"})," Loadingâ¦"]}),!o&&c.length===0&&e.jsx("div",{className:"text-center text-slate-400 py-12 text-sm",children:"No MA data available for this state."}),!o&&c.length>0&&e.jsx("div",{className:"px-5 py-4",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-slate-50 border-y border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500 w-12",children:"Rank"}),e.jsx("th",{className:"text-left px-3 py-2 font-medium text-slate-500",children:"County"}),e.jsx("th",{className:"text-right px-3 py-2 font-medium text-slate-500",children:d.label})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:c.map(i=>e.jsxs("tr",{className:i.is_subject?"bg-sky-50":"hover:bg-slate-50",ref:h=>{i.is_subject&&h&&typeof h.scrollIntoView=="function"&&setTimeout(()=>h.scrollIntoView({block:"center",behavior:"auto"}),50)},children:[e.jsxs("td",{className:`px-3 py-2 font-medium ${i.is_subject?"text-sky-700":"text-slate-500"}`,children:["#",i.rank]}),e.jsxs("td",{className:`px-3 py-2 ${i.is_subject?"font-semibold text-sky-800":"text-slate-700"}`,children:[i.county_name,i.is_subject&&e.jsx("span",{className:"ml-1.5 text-[9px] font-bold text-white bg-sky-600 px-1.5 py-0.5 rounded uppercase tracking-wide align-middle",children:"This facility"})]}),e.jsx("td",{className:`px-3 py-2 text-right font-mono ${i.is_subject?"font-bold text-sky-800":"text-slate-700"}`,children:d.fmt(i.value)})]},i.ssa))})]})})]})})}function to({rank:t,state:s,label:a}){const[n,r]=b.useState(!1);return e.jsxs("div",{className:"relative flex gap-2 mt-0.5",children:[e.jsxs("span",{className:`text-xs font-semibold cursor-help ${t.pctile<=25?"text-emerald-600":t.pctile>=75?"text-amber-600":"text-slate-700"}`,onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:["Top ",t.pctile,"%"]}),e.jsxs("span",{className:"text-xs text-slate-400",children:["in ",s," (",t.rank,"/",t.total,")"]}),n&&e.jsx("div",{className:"absolute z-50 bottom-full left-0 mb-1",style:{pointerEvents:"none"},children:e.jsx(rs,{pctile:t.pctile,rank:t.rank,total:t.total,state:s,title:a})})]})}function Ps({title:t,items:s,state:a,peers:n,currentCcn:r,compRanks:l}){return e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 bg-white",children:[e.jsx("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide mb-2",children:t}),e.jsx("div",{className:"space-y-3",children:s.map(({label:o,value:d,suffix:c,rank:m,footnote:p,compMetricKey:i})=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:o}),e.jsx("span",{className:"text-lg font-bold text-slate-800",children:d!=null?d.toFixed(1)+c:"â"})]}),d==null&&p&&e.jsx("p",{className:"text-xs text-slate-400 italic mt-0.5",children:p}),i&&l?.[i]&&e.jsx("div",{className:"mt-1",children:e.jsx(Dt,{compRank:l[i],metricKey:i,peers:n,currentCcn:r})}),m&&e.jsx(to,{rank:m,state:a,label:o})]},o))})]})}const so={occupancy:{label:"Occupancy %",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},rn_hprd:{label:"RN HPRD",fmt:t=>t?.toFixed(2)??"â"},total_nurse_hprd:{label:"Nurse HPRD",fmt:t=>t?.toFixed(2)??"â"},nurse_turnover:{label:"Turnover %",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},casemix:{label:"Case Mix",fmt:t=>t?.toFixed(3)??"â"},admin_turnover:{label:"Admin TO",fmt:t=>t?.toFixed(1)??"â"},rn_turnover:{label:"RN Turnover",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},vbp_multiplier:{label:"VBP Mult.",fmt:t=>t!=null?t.toFixed(4):"â"},don_tenure:{label:"DON Tenure",fmt:t=>t!=null?t>=365?(t/365).toFixed(1)+" yr":Math.round(t/30)+" mo":"â"},ss_rehosp:{label:"SS Rehosp %",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},ss_ed:{label:"SS ED %",fmt:t=>t!=null?t.toFixed(1)+"%":"â"},ls_hosp:{label:"LS Hosp",fmt:t=>t!=null?t.toFixed(1):"â"},ls_ed:{label:"LS ED",fmt:t=>t!=null?t.toFixed(1):"â"}},ao=new Set(["nurse_turnover","admin_turnover","rn_turnover","ss_rehosp","ss_ed","ls_hosp","ls_ed"]);function Dt({compRank:t,metricKey:s,peers:a,currentCcn:n,inline:r=!1}){const[l,o]=b.useState(!1),d=b.useRef(null);if(b.useEffect(()=>{if(!l)return;const p=i=>{d.current&&!d.current.contains(i.target)&&o(!1)};return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[l]),!t)return null;const c=so[s];if(!c)return null;const m=ao.has(s);return e.jsxs("div",{className:"relative inline-block",ref:d,children:[e.jsx("button",{onClick:p=>{p.stopPropagation(),o(!l)},className:r?"text-xs text-slate-500 hover:text-slate-700 hover:underline cursor-pointer":"text-xs text-slate-500 hover:underline cursor-pointer",children:r?e.jsxs("span",{className:"text-slate-500",children:["#",t.rank," of ",t.total," nearby"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"font-semibold text-slate-700",children:["#",t.rank]}),e.jsxs("span",{className:"text-slate-400",children:[" of ",t.total," nearby"]})]})}),l&&a?.length>0&&e.jsxs("div",{className:"absolute z-40 left-0 top-full mt-1 bg-white border border-slate-200 rounded-lg shadow-xl p-2 w-[calc(100vw-2rem)] md:w-80 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-xs font-semibold text-slate-500 px-2 py-1 uppercase",children:[c.label," â Nearby Facilities"]}),e.jsx("div",{className:"divide-y divide-slate-100",children:[...a].filter(p=>p[s]!=null).sort((p,i)=>m?p[s]-i[s]:i[s]-p[s]).map((p,i)=>e.jsxs("div",{className:`flex justify-between items-center px-2 py-1.5 text-xs rounded ${p.ccn===n?"bg-sky-50 font-semibold":""}`,children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-slate-400 w-4 text-right flex-shrink-0",children:i+1}),e.jsx("span",{className:"truncate text-slate-700",children:p.provider_name}),p.dist!=null&&p.dist>0&&e.jsxs("span",{className:"text-slate-400 flex-shrink-0",children:["(",p.dist,"mi)"]})]}),e.jsx("span",{className:"text-slate-600 flex-shrink-0 ml-2",children:c.fmt(p[s])})]},p.ccn))})]})]})}function rs({pctile:t,rank:s,total:a,state:n,title:r}){const p=[];for(let L=0;L<=50;L++){const D=L/50,j=10+D*200,f=10+48*(1-Math.exp(-Math.pow(D-.5,2)/.045)*.92);p.push(`${L===0?"M":"L"}${j.toFixed(1)},${f.toFixed(1)}`)}const i=p.join(" "),h=i+` L${210 .toFixed(1)},${58 .toFixed(1)} L10,${58 .toFixed(1)} Z`,v=10+t/100*200,y=t<=25?"#059669":t>=75?"#d97706":"#334155";return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-xl shadow-xl p-3",style:{width:236},children:[e.jsxs("div",{className:"text-xs font-semibold text-slate-700 mb-1",children:[r," Distribution"]}),e.jsxs("svg",{width:220,height:80,className:"block",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:`dist-grad-${t}`,x1:"0",y1:"0",x2:"1",y2:"0",children:[e.jsx("stop",{offset:"0%",stopColor:"#059669",stopOpacity:"0.15"}),e.jsx("stop",{offset:"25%",stopColor:"#059669",stopOpacity:"0.08"}),e.jsx("stop",{offset:"50%",stopColor:"#94a3b8",stopOpacity:"0.06"}),e.jsx("stop",{offset:"75%",stopColor:"#d97706",stopOpacity:"0.08"}),e.jsx("stop",{offset:"100%",stopColor:"#d97706",stopOpacity:"0.15"})]})}),e.jsx("path",{d:h,fill:`url(#dist-grad-${t})`}),e.jsx("path",{d:i,fill:"none",stroke:"#94a3b8",strokeWidth:"1.5"}),e.jsx("line",{x1:10,y1:58,x2:210,y2:58,stroke:"#e2e8f0",strokeWidth:"1"}),e.jsx("line",{x1:v,y1:12,x2:v,y2:58,stroke:y,strokeWidth:"2",strokeDasharray:"3,2"}),e.jsx("circle",{cx:v,cy:10+48*(1-Math.exp(-Math.pow(t/100-.5,2)/.045)*.92),r:"4",fill:y,stroke:"white",strokeWidth:"1.5"}),e.jsx("text",{x:10,y:78,fontSize:"9",fill:"#94a3b8",children:"Best"}),e.jsx("text",{x:210,y:78,fontSize:"9",fill:"#94a3b8",textAnchor:"end",children:"Lowest"}),(()=>{const L=t<=15?"start":t>=85?"end":"middle",D=t<=15?10:t>=85?210:v;return e.jsxs("text",{x:D,y:9,fontSize:"9",fill:y,textAnchor:L,fontWeight:"600",children:["#",s," of ",a]})})()]}),e.jsxs("div",{className:"text-xs text-slate-500 text-center mt-1",children:["Ranked among all ",a," SNFs in ",n]})]})}function Oe({title:t,titleTip:s,value:a,sub:n,stateRank:r,compRank:l,compMetricKey:o,peers:d,currentCcn:c,state:m}){const[p,i]=b.useState(!1);return e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 bg-white",children:[e.jsxs("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:[t,s&&e.jsxs(e.Fragment,{children:[" ",e.jsx(le,{text:s})]})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-slate-800",children:a??"â"}),n&&e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:n}),(r||l)&&e.jsxs("div",{className:"mt-1.5 text-xs text-slate-500 space-y-0.5",children:[r&&e.jsxs("div",{className:"relative",children:[e.jsxs("span",{className:"cursor-help",onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),children:["Top ",r.pctile,"% in ",m]}),p&&e.jsx("div",{className:"absolute z-50 bottom-full left-0 mb-1",style:{pointerEvents:"none"},children:e.jsx(rs,{pctile:r.pctile,rank:r.rank,total:r.total,state:m,title:t})})]}),l&&e.jsx("div",{children:e.jsx(Dt,{compRank:l,metricKey:o,peers:d,currentCcn:c,inline:!0})})]})]})}function et({title:t,value:s,pct:a,stateAvg:n,stateAvgRaw:r,rank:l,total:o,onRankClick:d,onTrendClick:c}){const m=a!=null&&n!=null?a>n:null,p=l!=null&&o!=null,i=n!=null||r;return e.jsxs("div",{className:"rounded-xl border border-slate-200 p-4 bg-white",children:[e.jsx("p",{className:"text-xs font-medium text-slate-500 uppercase tracking-wide",children:t}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-slate-800",children:s??"â"}),a!=null&&e.jsxs("p",{className:"text-xs text-slate-400 mt-0.5",children:[a.toFixed(1),"%"]}),(i||p)&&e.jsxs("div",{className:"mt-1.5 text-xs text-slate-500 flex items-center gap-1 flex-wrap",children:[i&&e.jsxs("span",{children:["State avg ",r||n?.toFixed(1)+"%",m!=null&&e.jsx("span",{className:"text-slate-400",children:m?" (above)":" (below)"})]}),i&&p&&e.jsx("span",{className:"text-slate-300",children:"·"}),p&&(d?e.jsxs("button",{type:"button",onClick:d,className:"text-slate-500 hover:text-slate-700 hover:underline",title:`See all ${o} counties ranked by ${t}`,children:["#",l," of ",o," counties â"]}):e.jsxs("span",{children:["#",l," of ",o," counties"]}))]}),c&&e.jsx("button",{type:"button",onClick:c,className:"text-xs text-sky-600 hover:text-sky-800 hover:underline mt-0.5 block",children:"View trend â"})]})}function ka({ssa:t,countyName:s,onClose:a}){const{data:n,isLoading:r}=ee({queryKey:["medicare-trend",t],queryFn:()=>mn({ssa_codes:String(t)}),enabled:!!t}),l=b.useMemo(()=>{const d=(n?.penetration_trend||[]).filter(h=>h.report_date&&h.eligibles!=null);if(!d.length)return[];const c=d[d.length-1].report_date.slice(5,7),m={};for(const h of d)h.report_date.slice(5,7)===c&&(m[+h.report_date.slice(0,4)]=h.eligibles);const p=Object.keys(m).map(Number).sort((h,v)=>h-v),i=[];for(let h=1;h<p.length;h++){const v=p[h],y=m[p[h-1]],L=m[v];y>0&&p[h]===p[h-1]+1&&i.push({year:String(v),"Growth %":Math.round((L-y)/y*1e3)/10})}return i},[n]),o=De(a);return Zt.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 bg-black/40 flex items-center justify-center p-4",onClick:a,children:e.jsxs("div",{ref:o,role:"dialog","aria-modal":"true","aria-labelledby":"medicare-trend-title",className:"bg-white rounded-lg shadow-lg max-w-2xl w-full p-5",onClick:d=>d.stopPropagation(),children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{id:"medicare-trend-title",className:"text-base font-semibold text-slate-800",children:"Medicare Population â Annual Growth"}),e.jsx("button",{onClick:a,"aria-label":"Close",className:"text-slate-400 hover:text-slate-700",children:e.jsx(Me,{size:18})})]}),e.jsxs("p",{className:"text-xs text-slate-400 mb-3",children:[s," â year-over-year % change in total Medicare beneficiaries"]}),r?e.jsxs("div",{className:"py-16 text-center text-slate-400",children:[e.jsx(ge,{className:"animate-spin inline mr-1",size:18})," Loading trendâ¦"]}):l.length===0?e.jsx("p",{className:"py-16 text-center text-slate-400 text-sm",children:"No trend data available for this county."}):e.jsx(je,{width:"100%",height:320,children:e.jsxs(it,{data:l,margin:{top:8,right:12,left:0,bottom:0},children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"year",tick:{fontSize:11}}),e.jsx(xe,{tick:{fontSize:11}
6,tickFormatter:d=>`${d>0?"+":""}${d}%`}),e.jsx(ce,{formatter:d=>`${d>0?"+":""}${d}%`,labelFormatter:d=>`${d} vs ${+d-1}`}),e.jsx(ss,{y:0,stroke:"#cbd5e1"}),e.jsx(_e,{dataKey:"Growth %",radius:[2,2,0,0],children:l.map((d,c)=>e.jsx(Ft,{fill:d["Growth %"]>=0?"#0ea5e9":"#94a3b8"},c))})]})})]})}),document.body)}function no({medicare:t,medicaid:s,other:a,total:n,maDays:r,managedMedicaidDays:l}){if(!n||n<=0)return null;const o=y=>((y||0)/n*100).toFixed(1),d=r!=null||l!=null,c=r||0,m=l||0,p=Math.max(0,(t||0)-c),i=Math.max(0,(s||0)-m),h=t&&r!=null?Math.round(c/t*100):null,v=d?[{label:"Medicare FFS",count:p,pct:o(p),color:"bg-slate-600"},{label:"Medicare Advantage",count:c,pct:o(c),color:"bg-indigo-500"},{label:"Medicaid FFS",count:i,pct:o(i),color:"bg-slate-400"},{label:"Managed Medicaid",count:m,pct:o(m),color:"bg-indigo-300"},{label:"Other",count:a||0,pct:o(a),color:"bg-slate-300"}]:[{label:"Medicare",count:t||0,pct:o(t),color:"bg-slate-600"},{label:"Medicaid",count:s||0,pct:o(s),color:"bg-slate-400"},{label:"Other",count:a||0,pct:o(a),color:"bg-slate-300"}];return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-sm font-semibold text-slate-700",children:"Payer Mix"}),e.jsxs("div",{className:"flex items-center gap-3",children:[h!=null&&e.jsxs("span",{className:"text-xs text-indigo-700 bg-indigo-50 border border-indigo-100 rounded-full px-2 py-0.5 font-medium",title:"Medicare Advantage share of Medicare days (managed-care penetration)",children:[h,"% MA"]}),e.jsxs("span",{className:"text-sm font-bold text-slate-800 tabular-nums",children:[n," residents"]})]})]}),e.jsx("div",{className:"flex h-2.5 rounded-full overflow-hidden mb-3 bg-slate-100",children:v.filter(y=>y.count>0).map(y=>e.jsx("div",{className:`${y.color} relative group cursor-default`,style:{width:`${y.pct}%`},children:e.jsxs("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-1 hidden group-hover:block bg-slate-800 text-white text-xs rounded px-2 py-1 whitespace-nowrap z-10 shadow-lg",children:[y.label,": ",y.count," (",y.pct,"%)"]})},y.label))}),e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-1.5",children:v.map(y=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx("span",{className:`h-2 w-2 rounded-full ${y.c
6olor}`}),e.jsx("span",{className:"text-slate-500",children:y.label}),e.jsx("span",{className:"font-semibold text-slate-700 tabular-nums",children:y.count}),e.jsxs("span",{className:"text-slate-400 tabular-nums",children:[y.pct,"%"]})]},y.label))})]})}function Sa({ccn:t}){const{data:s,isLoading:a}=ee({queryKey:["ma-contract-intel",t],queryFn:()=>un(t),enabled:!!t});if(a||!s?.contracts?.length)return null;const n=s.contracts.filter(l=>l.plan_enrolled>0||l.rate>0);if(!n.length)return null;const r=n.filter(l=>l.plan_enrolled>0);return e.jsxs("div",{className:"mt-4",children:[e.jsxs("p",{className:"text-xs font-semibold text-slate-600 uppercase tracking-wide mb-2 flex items-center gap-1",children:["Payer Rates vs MA Enrollment",e.jsx(le,{text:"Cross-references this facility's negotiated payer rates (code 0120, SNF Room & Board) with Medicare Advantage plan enrollment in the county. Shows which payers control the most MA lives and how this facility's rates compare to county medians. Use this for contract renegotiation intelligence.",size:11})]}),r.length>0?e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Payer"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Your Rate"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"County Med"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"vs Med"}),e.jsx("th",{scope:"col",className:"text-left px-3 py-1.5 text-xs font-semibold text-slate-500",children:"MA Plan"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Enrolled"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Share"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:r.slice(0,10).map((l,o)=>e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx("td",{className:"px-3 py-2",children:e.jsx("p",{className:"font-medium text-slate-700 text-xs capitalize",children:l.payer.replace(/_/g," ")})}),e.jsxs("td",{className:"px-3 py-2 text-right font-semibold text-slate-800 text-xs",children:["$",l.rate.toFixed(2)]}),e.jsx("td",{className:"px-3 py-2 text-right text-slate-500 text-xs",children:l.county_median_rate?`$${l.county_median_rate.toFixed(2)}`:"â"}),e.jsx("td",{className:"px-3 py-2 text-right",children:l.rate_vs_median!=null?e.jsxs("span",{className:`text-xs font-medium ${l.rate_vs_median>0?"text-emerald-600":l.rate_vs_median<0?"text-red-500":"text-slate-400"}`,children:[l.rate_vs_median>0?"+":"",l.rate_vs_median.toFixed(2)]}):"â"}),e.jsx("td",{className:"px-3 py-2",children:l.matched_plans.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-700",children:l.matched_plans[0].name}),l.matched_plans[0].parent&&e.jsx("p",{className:"text-[10px] text-slate-400",children:l.matched_plans[0].parent})]}):e.jsx("span",{className:"text-slate-300 text-xs",children:"â"})}),e.jsx("td",{className:"px-3 py-2 text-right text-xs text-slate-600",children:l.plan_enrolled.toLocaleString()}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("span",{className:`text-xs font-medium ${l.plan_share_pct>=20?"text-sky-600":"text-slate-500"}`,children:[l.plan_share_pct.toFixed(1),"%"]})})]},o))})]})}):e.jsx("p",{className:"text-xs text-slate-400 italic",children:"No matching MA plans found for this facility's payers in this county."}),n.filter(l=>l.plan_enrolled===0&&l.rate>0).length>0&&e.jsxs("details",{className:"mt-2",children:[e.jsxs("summary",{className:"text-[10px] text-slate-400 cursor-pointer hover:text-slate-600",children:[n.filter(l=>l.plan_enrolled===0).length," payers with rates but no matched MA plan"]}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:n.filter(l=>l.plan_enrolled===0).map((l,o)=>e.jsxs("span",{className:"text-[10px] bg-slate-100 text-slate-500 px-2 py-0.5 rounded capitalize",children:[l.payer.replace(/_/g," "),": $",l.rate.toFixed(2)]},o))})]})]})}function ro({f:t,onShowCompetitors:s,onDrillToTrends:a}){const[n,r]=b.useState(!1),[l,o]=b.useState(null),[d,c]=b.useState(null),[m,p]=b.useState(!1),i=t.competitor_rank?.peers,h=t.ccn,v=(()=>
6{const f=Number(t.number_of_certified_beds),w=Number(t.average_number_of_residents_per_day);return f>0&&w>0?(w/f*100).toFixed(1)+"%":"â"})(),y=(()=>{const f=t.rating_cycle_1_standard_survey_health_date;if(!f)return null;const w=new Date(f);return isNaN(w.getTime())?f.slice(0,10):w.toLocaleDateString("en-US",{month:"short",year:"numeric"})})(),L=(()=>{if(!t.rating_cycle_1_standard_survey_health_date)return null;const f=new Date(t.rating_cycle_1_standard_survey_health_date),w=new Date;return w.setFullYear(w.getFullYear()-2),f<w?"Y":"N"})(),D=f=>{if(f==null||f==="")return e.jsx("span",{className:"text-slate-400",children:"â"});const w=f==="Y"||f===!0||f==="true"||f==="Yes";return e.jsx("span",{className:w?"font-medium text-rose-600":"text-slate-700",children:w?"Yes":"No"})},j=[["CCRC",D(t.continuing_care_retirement_community)],["In hospital",D(t.provider_resides_in_hospital)],["Ownership change (12 mo)",D(t.provider_changed_ownership_in_last_12_months)],["Inspection > 2 years ago",D(L)],["Last inspection",y?e.jsx("span",{className:"text-slate-700",children:y}):e.jsx("span",{className:"text-slate-400",children:"â"})]],M=t.qm_short_stay_rehospitalization!=null||t.qm_long_stay_hospitalizations!=null||t.qm_short_stay_ed_visits!=null||t.qm_long_stay_ed_visits!=null||t.qm_footnotes;return e.jsxs("div",{className:"space-y-6",children:[n&&e.jsx(va,{ccn:t.ccn,facilityName:t.provider_name||t.ccn,onClose:()=>r(!1)}),l&&e.jsx(Na,{ccn:t.ccn,metric:l,facilityName:t.provider_name||t.ccn,onClose:()=>o(null)}),m&&e.jsx(ka,{ssa:t.ssa,countyName:t.county_name,onClose:()=>p(!1)}),d&&e.jsx(wa,{ccn:t.ccn,metric:d,facilityName:t.provider_name||t.ccn,reportDate:t.ma_report_date,onClose:()=>c(null)}),t.insight_score&&(()=>{const f=t.insight_score,w=f.score??0,B=w>=70?"emerald":w>=50?"sky":w>=35?"amber":"red",_={emerald:{text:"text-emerald-600",accent:"border-l-emerald-500",delta:"text-emerald-700"},sky:{text:"text-sky-700",accent:"border-l-sky-500",delta:"text-sky-800"},amber:{text:"text-amber-600",accent:"border-l-amber-500",delta:"text-amber-700"},red:{text:"text-red-600",accent:"border-l-red-500",delta:"text-red-700"}}[B],S=(100-(f.state_percentile||0)).toFixed(0),C=(100-(f.national_percentile||0)).toFixed(0);return e.jsx("div",{className:`rounded-xl border border-slate-200 border-l-4 ${_.accent} bg-white shadow-sm px-5 py-4`,children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-widest flex items-center gap-1",children:[e.jsx(lt,{to:"/insight-scores",className:"hover:text-sky-700 hover:underline transition-colors",title:"Open the national InsightScore explorer",children:"SNF InsightScore"}),e.jsx(le,{text:"A proprietary composite index measuring facility performance across clinical quality, staffing adequacy, trend momentum (ADC growth, turnover direction), market position relative to local and state peers, and financial sustainability â with an acuity adjustment for facilities serving higher-complexity residents. Scores are indexed on a 0-100 scale with state and national percentile rankings.",size:10,portal:!0})]}),e.jsxs("p",{className:`text-2xl font-bold tabular-nums ${_.text} leading-none`,children:[w.toFixed(0),e.jsx("span",{className:"text-sm font-medium text-slate-400 ml-0.5",children:"/ 100"})]}),f.delta!=null&&f.delta!==0&&e.jsxs("span",{className:`text-xs font-semibold leading-none ${_.delta}`,title:`${f.delta>0?"+":""}${f.delta} over ~60 days (vs ${f.prior_score}${f.prior_snapshot?` on ${f.prior_snapshot}`:""})`,children:[f.delta>0?"â²":"â¼"," ",f.delta>0?"+":"",f.delta.toFixed(1),e.jsx("span",{className:"font-normal text-slate-400",children:" · 60d"})]}),e.jsx("button",{type:"button",onClick:()=>r(!0),className:"text-[10px] font-semibold text-sky-600 hover:text-sky-800 hover:underline",title:"View this facility's InsightScore history over time",children:"View history â
6"})]}),e.jsxs("button",{type:"button",onClick:s,title:"Click to compare with local competitors",className:"flex items-center gap-4 rounded-md px-2 py-1 -mx-2 -my-1 transition-colors hover:bg-slate-50 focus:outline-none focus:ring-2 focus:ring-sky-500",children:[t.competitor_rank?.insight_score&&e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"Local"}),e.jsxs("p",{className:"text-sm font-bold text-slate-700 tabular-nums",children:["#",t.competitor_rank.insight_score.rank,e.jsxs("span",{className:"text-xs font-normal text-slate-400",children:[" of ",t.competitor_rank.insight_score.total]})]})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"State"}),e.jsxs("p",{className:"text-sm font-bold text-slate-700 tabular-nums",children:["top ",S,"%"]})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-500 uppercase tracking-wide",children:"National"}),e.jsxs("p",{className:"text-sm font-bold text-slate-700 tabular-nums",children:["top ",C,"%"]})]}),e.jsx("span",{className:"text-[10px] font-semibold text-sky-600 ml-1",children:"Compare â"})]})]})})})(),t.insight_score&&e.jsx(ja,{ccn:t.ccn,autoShowTop:!0}),e.jsxs("section",{children:[e.jsx("h2",{className:"section-heading",children:"CMS Star Ratings"}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-2",children:[{label:"Overall",val:t.overall_rating,tip:"CMS Five-Star composite of health inspection, staffing, and quality measure ratings.",seriesKey:"Overall"},{label:"Health Insp.",val:t.health_inspection_rating,tip:"Based on the two most recent health inspection survey cycles and complaint investigations.",seriesKey:"Health",note:t.rating_cycle_1_standard_survey_health_date?`Surveyed ${new Date(t.rating_cycle_1_standard_survey_health_date+"T00:00:00").toLocaleDateString("en-US")}`:null},{label:"Staffing",val:t.staffing_rating,tip:"Based on reported nursing staff hours per resident day (HPRD) including RN hours.",seriesKey:"Staffing"},{label:"Quality",val:t.qm_rating,tip:"Based on 11 quality measures derived from MDS assessments and Medicare claims data.",seriesKey:"QM"},{label:"Long Stay QM",val:t.longstay_qm_rating,seriesKey:"Long Stay QM"},{label:"Short Stay QM",val:t.shortstay_qm_rating,seriesKey:"Short Stay QM"}].map(({label:f,val:w,tip:B,seriesKey:z,note:_})=>{const S=!!a&&!!z;return e.jsxs("div",{onClick:S?()=>a(z):void 0,role:S?"button":void 0,tabIndex:S?0:void 0,onKeyDown:S?C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),a(z))}:void 0,className:`flex items-center justify-between gap-2 bg-white rounded-lg border border-slate-200 px-3 py-2 ${S?"cursor-pointer hover:border-sky-300 transition-colors":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"text-xs text-slate-600 flex items-center gap-1",children:[e.jsx("span",{className:"truncate",children:f}),B&&e.jsx(le,{text:B})]}),_&&e.jsx("span",{className:"block text-[10px] text-slate-400 leading-tight mt-0.5",children:_})]}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[e.jsx($t,{rating:w,size:"sm"}),e.jsx("span",{className:"text-xs text-slate-400 tabular-nums w-3 text-right",children:w??"â"})]})]},f)})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"section-heading",children:"Key Metrics"}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3",children:[e.jsx(Oe,{title:"Census & Occupancy",titleTip:"Average Daily Census divided by Certified Beds.",value:v,sub:`${t.number_of_certified_beds??"â"} beds · ${t.average_number_of_residents_per_day??"â"} ADC`,stateRank:t.state_rank?.occupancy,compRank:t.competitor_rank?.occupancy,compMetricKey:"occupancy",peers:i,currentCcn:h,state:t.state}),e.jsx(Oe,{title:"RN HPRD",titleTip:"Hours Per Resident Day â total nursing staff hours divided by resident census.",value:t.reported_rn_hprd?Number(t.reported_rn_hprd).toFixed(2):null,sub:"hours/resident/day",stateRank:t.state_rank?.rn_hprd,compRank:t.competitor_rank?.rn_hprd,compMetricKey:"rn_hprd",peers:i,currentCcn:h,state:t.state}),e.jsx(Oe,{title:"Total Nurse HPRD",titleTip:"Hours Per Resident Day â total nursing staff hours divided by resident census.",value:t.reported_total_nurse_hprd?Number(t.reported_total_nurse_hprd).toFixed(2):null,sub:"hours/resident/day",stateRank:t.state_rank?.total_nurse_hprd,compRank:t.competitor_rank?.total_nurse_hprd,compMetricKey:"total_nurse_hprd",peers:i,currentCcn:h,state:t.state}
6),e.jsx(Oe,{title:"Direct Care Turnover",titleTip:"Annual percentage of direct care nursing staff turnover (RN, LPN, CNA combined) based on CMS Payroll-Based Journal data.",value:t.total_nursing_staff_turnover?t.total_nursing_staff_turnover+"%":null,stateRank:t.state_rank?.nurse_turnover,compRank:t.competitor_rank?.nurse_turnover,compMetricKey:"nurse_turnover",peers:i,currentCcn:h,state:t.state}),e.jsx(Oe,{title:"Nursing Acuity",value:t.nursing_casemix_index_ratio,titleTip:"CMS Nursing Case-Mix Index â measures the clinical complexity of the resident population. A value of 1.00 is the national baseline. Above 1.00 means higher-acuity residents requiring more intensive nursing care; below 1.00 means lower acuity. This is NOT the same as the PDPM case-mix index used for Medicare reimbursement.",sub:"1.00 = national baseline",stateRank:t.state_rank?.casemix,compRank:t.competitor_rank?.casemix,compMetricKey:"casemix",peers:i,currentCcn:h,state:t.state}),e.jsx(Oe,{title:"VBP Multiplier",titleTip:"CMS SNF Value-Based Purchasing incentive payment multiplier applied to all Medicare Part A payments. Above 1.00 = bonus. Below 1.00 = penalty. Based on readmission rates, infections, turnover, and staffing.",value:t.vbp?t.vbp.multiplier.toFixed(4):null,sub:t.vbp?`${t.vbp.multiplier>=1?"+":""}${((t.vbp.multiplier-1)*100).toFixed(2)}% ${t.vbp.multiplier>=1?"bonus":"penalty"}`:null,stateRank:t.vbp?.state_pctile!=null?{pctile:t.vbp.state_pctile,rank:Math.round(t.vbp.state_total*t.vbp.state_pctile/100)+1,total:t.vbp.state_total}:null,compRank:t.competitor_rank?.vbp_multiplier,compMetricKey:"vbp_multiplier",peers:i,currentCcn:h,state:t.state}),e.jsx(Oe,{title:"Admin Departures",value:t.administrator_turnover!=null?t.administrator_turnover:null,sub:"in last 12 months",stateRank:t.state_rank?.admin_turnover,compRank:t.competitor_rank?.admin_turnover,compMetricKey:"admin_turnover",peers:i,currentCcn:h,state:t.state}),e.jsx(Oe,{title:"DON Tenure",titleTip:"Current Director of Nursing tenure from PBJ payroll data. Gap-aware â 180+ day gaps reset the clock.",value:t.don_tenure_days!=null?t.don_tenure_days>=365?`${(t.don_tenure_days/365).toFixed(1)} yr`:`${Math.round(t.don_tenure_days/30)} mo`:null,sub:t.don_tenure_days!=null?`${t.don_tenure_days} days`:null,stateRank:t.don_tenure_rank?{pctile:Math.round(100-t.don_tenure_rank.pctile),rank:Math.round(t.don_tenure_rank.total*(1-t.don_tenure_rank.pctile/100))+1,total:t.don_tenure_rank.total}:null,compRank:t.competitor_rank?.don_tenure,compMetricKey:"don_tenure",peers:i,currentCcn:h,state:t.state})]})]}),M&&e.jsxs("section",{children:[e.jsx("h2",{className:"section-heading",children:"Quality Measures"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsx(Ps,{title:"Short-Stay Outcomes",items:[{label:"Rehospitalization",value:t.qm_short_stay_rehospitalization,suffix:"%",rank:t.qm_rank?.["521"],footnote:t.qm_footnotes?.["521"],compMetricKey:"ss_rehosp"},{label:"ED Visits",value:t.qm_short_stay_ed_visits,suffix:"%",rank:t.qm_rank?.["522"],footnote:t.qm_footnotes?.["522"],compMetricKey:"ss_ed"}],state:t.state,peers:t.competitor_rank?.peers,currentCcn:t.ccn,compRanks:t.competitor_rank}
6),e.jsx(Ps,{title:"Long-Stay Outcomes",items:[{label:"Hospitalizations",value:t.qm_long_stay_hospitalizations,suffix:"/1k days",rank:t.qm_rank?.["551"],footnote:t.qm_footnotes?.["551"],compMetricKey:"ls_hosp"},{label:"ED Visits",value:t.qm_long_stay_ed_visits,suffix:"/1k days",rank:t.qm_rank?.["552"],footnote:t.qm_footnotes?.["552"],compMetricKey:"ls_ed"}],state:t.state,peers:t.competitor_rank?.peers,currentCcn:t.ccn,compRanks:t.competitor_rank})]})]}),t.cr_census_total!=null&&t.cr_census_total>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"section-heading",children:["Census by Payer â Last Cost Report",t.cr_census_fy_year&&e.jsxs("span",{className:"text-xs font-normal text-slate-400 ml-2",children:["(FY ",t.cr_census_fy_year,")"]})]}),e.jsx(no,{medicare:t.cr_census_medicare,medicaid:t.cr_census_medicaid,other:t.cr_census_other,total:t.cr_census_total,maDays:t.cr_census_ma,managedMedicaidDays:t.cr_census_managed_medicaid})]}),(t.county_total_pop||t.ma_penetration!=null)&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[t.county_total_pop?e.jsxs("section",{children:[e.jsxs("h2",{className:"section-heading",children:["County Demographics â ",t.county_name]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(et,{title:"Total Population",value:t.county_total_pop?.toLocaleString(),stateAvgRaw:t.state_avg_total_pop?.toLocaleString(),rank:t.county_rank_total_pop,total:t.state_county_count,onRankClick:()=>o("total_pop")}),e.jsx(et,{title:"Pop. 65+",value:t.county_pop_65_plus?.toLocaleString(),pct:t.county_pct_65_plus,stateAvg:t.state_avg_pct_65_plus,rank:t.county_rank_pct_65,total:t.state_county_count,onRankClick:()=>o("pct_65_plus")}),e.jsx(et,{title:"Pop. 85+",value:t.county_pop_85_plus?.toLocaleString(),stateAvgRaw:t.state_avg_pop_85_plus?.toLocaleString(),rank:t.county_rank_pop_85_plus,total:t.state_county_count,onRankClick:()=>o("pop_85_plus")}),e.jsx(et,{title:"Median HHI",value:t.county_median_hhi?"$"+t.county_median_hhi.toLocaleString():null,stateAvgRaw:t.state_avg_median_hhi?"$"+t.state_avg_median_hhi.toLocaleString():null,rank:t.county_rank_median_hhi,total:t.state_county_count,onRankClick:()=>o("median_hhi")}),e.jsx(et,{title:"Medicare Pop. Growth (YoY)",value:t.county_medicare_yoy_growth!=null?(t.county_medicare_yoy_growth>0?"+":"")+t.county_medicare_yoy_growth.toFixed(1)+"%":null,stateAvgRaw:t.state_avg_medicare_yoy_growth!=null?(t.state_avg_medicare_yoy_growth>0?"+":"")+t.state_avg_medicare_yoy_growth.toFixed(1)+"%":null,rank:t.county_rank_medicare_growth,total:t.county_medicare_growth_total,onRankClick:()=>c("medicare_growth"),onTrendClick:t.ssa?()=>p(!0):void 0}),e.jsx(et,{title:"Poverty Rate",value:t.county_total_pop&&t.county_pop_below_poverty?(t.county_pop_below_poverty/t.county_total_pop*100).toFixed(1)+"%":null,stateAvgRaw:t.state_avg_poverty_rate!=null?t.state_avg_poverty_rate.toFixed(1)+"%":t.state_avg_pop_below_poverty&&t.state_avg_total_pop?(t.state_avg_pop_below_poverty/t.state_avg_total_pop*100).toFixed(1)+"%":null,rank:t.county_rank_poverty_rate??t.county_rank_below_poverty,total:t.state_county_count,onRankClick:()=>o("poverty_rate")})]})]}):e.jsx("div",{}),t.ma_penetration!=null?e.jsxs("section",{children:[e.jsxs("h2",{className:"section-heading",children:["Medicare Advantage â ",t.ma_report_date]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 mb-3",children:[e.jsx(Et,{title:"MA Penetration",value:t.ma_penetration.toFixed(1)+"%",accent:!0,sub:t.ma_rank_penetration!=null&&t.ma_state_county_count!=null?`#${t.ma_rank_penetration}/${t.ma_state_county_count} in state`:void 0,onSubClick:t.ma_rank_penetration!=null?()=>c("ma_penetration"):void 0,subTitle:"See all counties in state ranked by MA penetration"}),e.jsx(Et,{title:"MA Enrolled",value:t.ma_county_enrolled?.toLocaleString(),accent:!0,sub:t.ma_rank_enrolled!=null&&t.ma_state_county_count!=null?`#${t.ma_rank_enrolled}/${t.ma_state_county_count} in state`:void 0,onSubClick:t.ma_rank_enrolled!=null?()=>c("ma_enrolled"):void 0,subTitle:"See all counties in state ranked by MA enrollment"}),t.ma_top_plans?.length>0&&(()=>{const f=t.ma_top_plans[0],w=f.enrolled&&t.ma_county_enrolled?f.enrolled/t.ma_county_enrolled*100:null,B=t.ma_to
6p_plan_share_rank;return e.jsx(Et,{title:"Top Plan Share",value:w!=null?w.toFixed(0)+"%":"â",accent:!0,sub:`${f.organization_marketing_name||f.contract_id}${B?` · #${B.rank}/${B.total} in state`:""}`,onSubClick:B?()=>c("top_plan_share"):void 0,subTitle:"See all counties in state ranked by top-plan share"})})()]}),t.ma_top_plans?.length>0&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-600 px-3 py-2 border-b border-slate-100 uppercase tracking-wide",children:"Top Plans"}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Plan"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Enrolled"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"Share"}),e.jsx("th",{scope:"col",className:"text-right px-3 py-1.5 text-xs font-semibold text-slate-500",children:"YoY"})]})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:t.ma_top_plans.slice(0,5).map((f,w)=>{const B=f.enrolled&&t.ma_county_enrolled?f.enrolled/t.ma_county_enrolled*100:null,z=f.enrolled!=null&&f.enrolled_prior_year!=null?f.enrolled-f.enrolled_prior_year:null,_=f.parent_organization||f.organization_marketing_name,S=_?`/ma?tab=${encodeURIComponent("Plan Explorer")}&org=${encodeURIComponent(_)}`:null;return e.jsxs("tr",{children:[e.jsxs("td",{className:"px-3 py-2",children:[S?e.jsxs("a",{href:S,className:"font-medium text-slate-700 hover:text-slate-900 hover:underline",title:`View ${_} in MA Plan Explorer`,children:[f.organization_marketing_name??f.contract_id," â"]}):e.jsx("p",{className:"font-medium text-slate-700",children:f.organization_marketing_name??f.contract_id}),e.jsx("p",{className:"text-xs text-slate-400",children:f.plan_type})]}),e.jsx("td",{className:"px-3 py-2 text-right text-slate-600 font-medium",children:f.enrolled?.toLocaleString()??"â"}),e.jsx("td",{className:"px-3 py-2 text-right text-slate-500",children:B!=null?B.toFixed(1)+"%":"â"}),e.jsx("td",{className:"px-3 py-2 text-right",children:z!=null?e.jsxs("span",{className:`font-medium ${z>0?"text-emerald-600":z<0?"text-red-500":"text-slate-400"}`,children:[z>0?"+":"",z.toLocaleString()]}):e.jsx("span",{className:"text-slate-300",children:"â"})})]},w)})})]})]}),e.jsx(Sa,{ccn:t.ccn}),e.jsxs("a",{href:`/ma?state=${t.state}${t.ssa?`&county=${t.ssa}`:""}`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 mt-3 text-xs font-medium text-sky-600 hover:text-sky-800 hover:underline",children:["View MA trends for ",t.county_name||t.state," ",e.jsx(gt,{size:14})]})]}):e.jsx("div",{})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"section-heading",children:"Classification"}),e.jsx("div",{className:"bg-white border border-slate-200 rounded-xl shadow-sm p-4 text-sm flex flex-wrap gap-x-6 gap-y-2",children:j.map(([f,w],B)=>e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-slate-500 font-semibold",children:f}),w]},B))})]})]})}const Qe=(...t)=>t.filter(Boolean).join(" ");function Ve({id:t,eyebrow:s,title:a,aside:n,children:r,className:l=""}){return e.jsxs("section",{id:t,className:Qe("scroll-mt-28",l),children:[e.jsxs("div",{className:"mb-5 flex items-end justify-between gap-4 border-b border-border pb-3",children:[e.jsxs("div",{className:"min-w-0",children:[s&&e.jsx("div",{className:"mb-1.5 font-mono text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground",children:s}),e.jsx("h2",{className:"text-pretty text-xl font-bold tracking-tight text-foreground",children:a})]}),n&&e.jsx("div",{className:"shrink-0",children:n})]}),r]})}const Rs={positive:"bg-positive-soft text-positive border-positive/25",negative:"bg-negative-soft text-negative border-negative/25",warning:"bg-warning-soft text-warning border-warning/30",neutral:"bg-secondary text-secondary-foreground border-border"};function Ca({children:t,tone:s="neutral",className:a=""}){return e.jsx("span",{className:Qe("inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 font-mono text-[11px] font-medium tabular",Rs[s]||Rs.neutral,a),children:t})}function lo({f:t,onShowHistory:s,onShowCompetitors:a}){if(!t?.insight_score)return null;const n=t.insight_score,r=n.score??0,l=(100-(n.state_percentile||0)).toFixed(0),o=(100-(n.national_percentile||0)).toFixed(0),d=[t.competitor_rank?.insight_score&&{scope:"Local",val:`#${t.competitor_rank.insight_score.rank}`,note:`of ${t.competitor_rank.insight_score.total}`},{scope:"State",val:`Top ${l}%`},{scope:"National",val:`Top ${o}%`}
6].filter(Boolean);return e.jsxs("div",{className:"w-full shrink-0 rounded-xl border border-border bg-secondary/40 p-4 sm:w-[340px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx(lt,{to:"/insight-scores",className:"truncate font-mono text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground transition-colors hover:text-foreground",title:"Open the national InsightScore explorer",children:"SNF InsightScore"}),e.jsx(le,{text:"A proprietary composite index measuring facility performance across clinical quality, staffing adequacy, trend momentum (ADC growth, turnover direction), market position relative to local and state peers, and financial sustainability â with an acuity adjustment for facilities serving higher-complexity residents. Scores are indexed on a 0-100 scale with state and national percentile rankings.",size:10,portal:!0})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2 font-mono text-[11px] text-primary",children:[e.jsx("button",{type:"button",onClick:s,className:"hover:underline",title:"View this facility's InsightScore history over time",children:"History"}),e.jsx("button",{type:"button",onClick:a,className:"hover:underline",title:"Compare with local competitors",children:"Compare"})]})]}),e.jsxs("div",{className:"mt-2 flex items-end justify-between gap-4",children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"font-mono text-4xl font-semibold tabular leading-none text-foreground",children:r.toFixed(0)}),e.jsx("span",{className:"font-mono text-base text-muted-foreground",children:"/100"})]}),n.delta!=null&&n.delta!==0&&e.jsxs("div",{className:"flex items-center gap-1.5",title:`${n.delta>0?"+":""}${n.delta} over ~60 days (vs ${n.prior_score}${n.prior_snapshot?` on ${n.prior_snapshot}`:""})`,children:[e.jsxs(Ca,{tone:n.delta>0?"positive":"negative",children:[n.delta>0?e.jsx(Vs,{size:11}):e.jsx(Ws,{size:11}),n.delta>0?"+":"",n.delta.toFixed(1)]}),e.jsx("span",{className:"font-mono text-[10px] text-muted-foreground",children:"60d"})]})]}),e.jsx("div",{className:"mt-3 grid grid-cols-3 gap-px overflow-hidden rounded-lg border border-border bg-border",children:d.map(c=>e.jsxs("button",{type:"button",onClick:a,title:"Compare with local competitors",className:"bg-card px-2 py-1.5 text-center transition-colors hover:bg-secondary/60",children:[e.jsx("div",{className:"font-mono text-[10px] uppercase tracking-wide text-muted-foreground",children:c.scope}),e.jsxs("div",{className:"mt-0.5 font-mono text-sm font-semibold tabular text-foreground",children:[c.val,c.note&&e.jsxs("span",{className:"font-normal text-muted-foreground",children:[" ",c.note]})]})]},c.scope))})]})}const io=t=>t==null?"neutral":t<=25?"positive":t>=75?"warning":"neutral";function Ma({stateRank:t,state:s,title:a}){const[n,r]=b.useState(!1);return t?e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"cursor-help",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),children:e.jsxs(Ca,{tone:io(t.pctile),children:["Top ",t.pctile,"% · ",s]})}),n&&e.jsx("div",{className:"absolute z-50 bottom-full left-0 mb-1",style:{pointerEvents:"none"},children:e.jsx(rs,{pctile:t.pctile,rank:t.rank,total:t.total,state:s,title:a})})]}):null}function Ee({title:t,titleTip:s,value:a,unit:n,sub:r,tone:l,stateRank:o,compRank:d,compMetricKey:c,peers:m,currentCcn:p,state:i}){const h=l==="negative"?"text-negative":l==="warning"||o&&o.pctile>=75?"text-warning":"text-foreground";return e.jsxs("div",{className:"group flex flex-col bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"text-[12px] font-semibold leading-tight text-foreground",children:t}),s&&e.jsx("span",{title:s,className:"shrink-0 cursor-help",children:e.jsx(Ye,{className:"size-3.5 text-muted-foreground/50 transition-colors group-hover:text-muted-foreground"})})]}),e.jsxs("div",{className:"mt-3 flex items-baseline gap-1",children:[e.jsx("span",{className:Qe("font-mono text-3xl font-semibold tabular leading-none",h),children:a??"â"}),n&&e.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:n})]}),r&&e.jsx("div",{className:"mt-1.5 font-mono text-[11px] tabular text-muted-foreground",children:r}),e.jsxs("div",{className:"mt-auto flex flex-wrap items-center gap-1.5 pt-4",children:[e.jsx(Ma,{stateRank:o,state:i,title:t}),d&&e.jsx(Dt,{compRank:d,metricKey:c,peers:m,currentCcn:p,inline:!0})]})]})}function Nt({label:t,value:s,suffix:a,rank:n,footnote:r,compMetricKey:l,compRanks:o,peers:d,currentCcn:c,state:m,last:p}){const i=s!=null;return e.jsxs("div",{className:Qe("flex items-center justify-between gap-4 px-4 py-3",!p&&"border-b border-border"),children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1 text-[13px] font-medium text-foreground",children:[t,r&&e.jsx(le,{text:`CMS footnote ${r}`})]}),l&&o?.[l]&&e.jsx("div",{className:"mt-0.5",children:e.jsx(Dt,{compRank:o[l],metricKey:l,peers:d,currentCcn:c,inline:!0})})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[n&&e.jsx(Ma,{stateRank:n,state:m,title:t}),e.jsxs("div",{className:"w-24 text-right",children:[e.jsx("span",{className:"font-mono text-xl font-semibold tabular text-foreground",children:i?Number(s).toFixed(1):"â"}),i&&a&&e.jsx("span",{className:"ml-0.5 font-mono text-[11px] text-muted-foreground",children:a})]})]})]})}function tt({title:t,value:s,pct:a,stateAvg:n,stateAvgRaw:r,rank:l,total:o,onRankClick:d,onTrendClick:c}){const m=r??(n!=null?n+"%":null);return e.jsxs("div",{className:"flex flex-col bg-card p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("span",{className:"text-[12px] font-medium leading-tight text-muted-foreground",children:t}),c&&e.jsx("button",{type:"button",onClick:c,className:"shrink-0 text-muted-foreground hover:text-foreground",title:"View Medicare population trend",children:e.jsx(hn,{size:13})})]}),e.jsxs("div",{className:"mt-2 font-mono text-2xl font-semibold tabular text-foreground",children:[s??"â",a!=null&&e.jsxs("span",{className:"ml-1 font-mono text-sm text-muted-foreground",children:["(",a.toFixed(1),"%)"]})]}),m!=null&&e.jsxs("div",{className:"mt-1 font-mono text-[11px] tabular text-muted-foreground",children:["State avg ",m]}),l!=null&&e.jsxs("button",{type:"button",onClick:d,className:"mt-auto flex items-center gap-1 pt-3 font-mono text-[11px] tabular text-primary hover:underline",title:"See all c
6ounties in state ranked",children:["#",l,o?` of ${o}`:""," in state ",e.jsx(pa,{size:11})]})]})}function zt({title:t,value:s,sub:a,onSubClick:n,subTitle:r}){return e.jsxs("div",{className:"bg-card p-4",children:[e.jsx("div",{className:"text-[12px] font-medium text-muted-foreground",children:t}),e.jsx("div",{className:"mt-2 font-mono text-2xl font-semibold tabular text-foreground",children:s??"â"}),a&&(n?e.jsx("button",{type:"button",onClick:n,title:r,className:"mt-1 block text-left font-mono text-[11px] tabular text-primary hover:underline",children:a}):e.jsx("div",{className:"mt-1 font-mono text-[11px] tabular text-muted-foreground",children:a}))]})}function oo({f:t,onShowCompetitors:s,onDrillToTrends:a}){const[n,r]=b.useState(null),[l,o]=b.useState(null),[d,c]=b.useState(!1),m=t.competitor_rank?.peers,p=t.ccn,i=(()=>{const M=Number(t.number_of_certified_beds),f=Number(t.average_number_of_residents_per_day);return M>0&&f>0?(f/M*100).toFixed(1)+"%":"â"})(),h=(()=>{const M=t.rating_cycle_1_standard_survey_health_date;if(!M)return null;const f=new Date(M);return isNaN(f.getTime())?M.slice(0,10):f.toLocaleDateString("en-US",{month:"short",year:"numeric"})})(),v=(()=>{if(!t.rating_cycle_1_standard_survey_health_date)return null;const M=new Date(t.rating_cycle_1_standard_survey_health_date),f=new Date;return f.setFullYear(f.getFullYear()-2),M<f?"Y":"N"})(),y=M=>{if(M==null||M==="")return e.jsx("span",{className:"text-muted-foreground",children:"â"});const f=M==="Y"||M===!0||M==="true"||M==="Yes";return e.jsxs("span",{className:Qe("inline-flex items-center gap-1.5",f?"font-medium text-negative":"text-foreground"),children:[f?e.jsx(Me,{className:"size-3.5 text-negative"}):e.jsx(pn,{className:"size-3.5 text-positive"}),f?"Yes":"No"]})},L=[["CCRC",y(t.continuing_care_retirement_community)],["In hospital",y(t.provider_resides_in_hospital)],["Ownership change (12 mo)",y(t.provider_changed_ownership_in_last_12_months)],["Inspection > 2 years",y(v)],["Last inspection",h?e.jsx("span",{className:"text-foreground",children:h}):e.jsx("span",{className:"text-muted-foreground",children:"â"})]],D=t.qm_short_stay_rehospitalization!=null||t.qm_long_stay_hospitalizations!=null||t.qm_short_stay_ed_visits!=null||t.qm_long_stay_ed_visits!=null||t.qm_footnotes,j=[{key:"Medicare",count:t.cr_census_medicare,color:"bg-chart-1"},{key:"Medicaid",count:t.cr_census_medicaid,color:"bg-chart-2"},{key:"Other",count:t.cr_census_other,color:"bg-chart-4"}].filter(M=>M.count!=null&&t.cr_census_total>0);return e.jsxs("div",{className:"flex flex-col",children:[n&&e.jsx(Na,{ccn:t.ccn,metric:n,facilityName:t.provider_name||t.ccn,onClose:()=>r(null)}),d&&e.jsx(ka,{ssa:t.ssa,countyName:t.county_name,onClose:()=>c(!1)}),l&&e.jsx(wa,{ccn:t.ccn,metric:l,facilityName:t.provider_name||t.ccn,reportDate:t.ma_report_date,onClose:()=>o(null)}),e.jsxs("div",{className:"flex flex-col divide-y divide-border [&>*]:py-10 [&>*:first-child]:pt-0 [&>*:last-child]:pb-0",children:[t.insight_score&&e.jsx(ja,{ccn:t.ccn,autoShowTop:!0,variant:"terminal"}),e.jsx(Ve,{eyebrow:"Regulatory Scorecard",title:"CMS Five-Star Ratings",aside:a&&e.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:"Click a rating for its trend"}),children:e.jsx("div",{className:"grid grid-cols-2 gap-2 lg:grid-cols-3",children:[{label:"Overall",val:t.overall_rating,tip:"CMS Five-Star composite of health inspection, staffing, and quality measure ratings.",seriesKey:"Overall"},{label:"Health Insp.",val:t.health_inspection_rating,tip:"Based on the two most recent health inspection survey cycles and complaint investigations.",seriesKey:"Health",note:t.rating_cycle_1_standard_survey_health_date?`Surveyed ${new Date(t.rating_cycle_1_standard_survey_health_date+"T00:00:00").toLocaleDateString("en-US")}`:null},{label:"Staffing",val:t.staffing_rating,tip:"Based on reported nursing staff hours per resident day (HPRD) including RN hours.",seriesKey:"Staffing"},{label:"Quality",val:t.qm_rating,tip:"Based on 11 quality measures derived from MDS assessments and Medicare claims data.",seriesKey:"QM"},{label:"Long Stay QM",val:t.longstay_qm_rating,seriesKey:"Long Stay QM"},{label:"Short Stay QM",val:t.shortstay_qm_rating,seriesKey:"Short Stay QM"}].map(({label:M,val:f,tip:w,seriesKey:B,note:z})=>{const _=!!a&&!!B;return e.jsxs("div",{onClick:_?()=>a(B):void 0,role:_?"button":void 0,tabIndex:_?0:void 0,onKeyDown:_?S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),a(B))}:void 0,className:Qe("flex items-center justify-between gap-2 rounded-lg border border-border bg-card px-3 py-2",_&&"cursor-pointer transition-colors hover:border-primary/40"),children:[e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"truncate",children:M}),w&&e.jsx(le,{text:w})]}),z&&e.jsx("span",{className:"mt-0.5 block text-[10px] leading-tight text-muted-foreground",children:z})]}),e.jsxs("span",{className:"flex shrink-0 items-center gap-1.5",children:[e.jsx($t,{rating:f,size:"sm"}),e.jsx("span",{className:"w-3 text-right font-mono text-xs tabular text-foreground",children:f??"â"})]})]},M)})})}),e.jsx(Ve,{eyebrow:"Operating & Regulatory KPIs",title:"Key Metrics",aside:e.jsx("span",{className:"font-mono text-[11px] text-muted-foreground",children:"Hover / click ranks for detail"}),children:e.jsxs("div",{className:"grid grid-cols-1 gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(Ee,{title:"Census & Occupancy",titleTip:"Average Daily Census divided by Certified Beds.",value:i,sub:`${t.number_of_certified_beds??"â"} beds · ${t.average_number_of_residents_per_day??"â"} ADC`,stateRank:t.state_rank?.occupancy,compRank:t.competitor_rank?.occupancy,compMetricKey:"occupancy",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"RN HPRD",titleTip:"Hours Per Resident Day â total nursing staff hours divided by resident census.",value:t.reported_rn_hprd?Number(t.reported_rn_hprd).toFixed(2):null,sub:"hours / resident / day",
6stateRank:t.state_rank?.rn_hprd,compRank:t.competitor_rank?.rn_hprd,compMetricKey:"rn_hprd",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"Total Nurse HPRD",titleTip:"Hours Per Resident Day â total nursing staff hours divided by resident census.",value:t.reported_total_nurse_hprd?Number(t.reported_total_nurse_hprd).toFixed(2):null,sub:"hours / resident / day",stateRank:t.state_rank?.total_nurse_hprd,compRank:t.competitor_rank?.total_nurse_hprd,compMetricKey:"total_nurse_hprd",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"Direct Care Turnover",titleTip:"Annual percentage of direct care nursing staff turnover (RN, LPN, CNA combined) based on CMS Payroll-Based Journal data.",value:t.total_nursing_staff_turnover?t.total_nursing_staff_turnover+"%":null,stateRank:t.state_rank?.nurse_turnover,compRank:t.competitor_rank?.nurse_turnover,compMetricKey:"nurse_turnover",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"Nursing Acuity",value:t.nursing_casemix_index_ratio,titleTip:"CMS Nursing Case-Mix Index â measures the clinical complexity of the resident population. A value of 1.00 is the national baseline. Above 1.00 means higher-acuity residents requiring more intensive nursing care; below 1.00 means lower acuity. This is NOT the same as the PDPM case-mix index used for Medicare reimbursement.",sub:"1.00 = national baseline",stateRank:t.state_rank?.casemix,compRank:t.competitor_rank?.casemix,compMetricKey:"casemix",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"VBP Multiplier",tone:t.vbp&&t.vbp.multiplier<1?"negative":void 0,titleTip:"CMS SNF Value-Based Purchasing incentive payment multiplier applied to all Medicare Part A payments. Above 1.00 = bonus. Below 1.00 = penalty. Based on readmission rates, infections, turnover, and staffing.",value:t.vbp?t.vbp.multiplier.toFixed(4):null,sub:t.vbp?`${t.vbp.multiplier>=1?"+":""}${((t.vbp.multiplier-1)*100).toFixed(2)}% ${t.vbp.multiplier>=1?"bonus":"penalty"}`:null,stateRank:t.vbp?.state_pctile!=null?{pctile:t.vbp.state_pctile,rank:Math.round(t.vbp.state_total*t.vbp.state_pctile/100)+1,total:t.vbp.state_total}:null,compRank:t.competitor_rank?.vbp_multiplier,compMetricKey:"vbp_multiplier",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"Admin Departures",value:t.administrator_turnover!=null?t.administrator_turnover:null,sub:"in last 12 months",stateRank:t.state_rank?.admin_turnover,compRank:t.competitor_rank?.admin_turnover,compMetricKey:"admin_turnover",peers:m,currentCcn:p,state:t.state}),e.jsx(Ee,{title:"DON Tenure",titleTip:"Current Director of Nursing tenure from PBJ payroll data. Gap-aware â 180+ day gaps reset the clock.",value:t.don_tenure_days!=null?t.don_tenure_days>=365?`${(t.don_tenure_days/365).toFixed(1)} yr`:`${Math.round(t.don_tenure_days/30)} mo`:null,sub:t.don_tenure_days!=null?`${t.don_tenure_days} days`:null,stateRank:t.don_tenure_rank?{pctile:Math.round(100-t.don_tenure_rank.pctile),rank:Math.round(t.don_tenure_rank.total*(1-t.don_tenure_rank.pctile/100))+1,total:t.don_tenure_rank.total}:null,compRank:t.competitor_rank?.don_tenure,compMetricKey:"don_tenure",peers:m,currentCcn:p,state:t.state})]})}),D&&e.jsx(Ve,{eyebrow:"MDS & Claims-Derived Outcomes",title:"Quality Measures",children:e.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:[e.jsx("div",{className:"border-b border-border px-4 py-2.5 font-mono text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground",children:"Short-Stay Outcomes"}),e.jsx(Nt,{label:"Rehospitalization",value:t.qm_short_stay_rehospitalization,suffix:"%",rank:t.qm_rank?.["521"],footnote:t.qm_footnotes?.["521"],compMetricKey:"ss_rehosp",compRanks:t.competitor_rank,peers:m,currentCcn:p,state:t.state}),e.jsx(Nt,{label:"ED Visits",value:t.qm_short_stay_ed_visits,suffix:"%",rank:t.qm_rank?.["522"],footnote:t.qm_footnotes?.["522"],compMetricKey:"ss_ed",compRanks:t.competitor_rank,peers:m,currentCcn:p,state:t.state,last:!0})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-border bg-card",children:[e.jsx("div",{className:"border-b border-border px-4 py-2.5 font-mono text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground",children:"Long-Stay Outcomes"}
6),e.jsx(Nt,{label:"Hospitalizations",value:t.qm_long_stay_hospitalizations,suffix:"/1k days",rank:t.qm_rank?.["551"],footnote:t.qm_footnotes?.["551"],compMetricKey:"ls_hosp",compRanks:t.competitor_rank,peers:m,currentCcn:p,state:t.state}),e.jsx(Nt,{label:"ED Visits",value:t.qm_long_stay_ed_visits,suffix:"/1k days",rank:t.qm_rank?.["552"],footnote:t.qm_footnotes?.["552"],compMetricKey:"ls_ed",compRanks:t.competitor_rank,peers:m,currentCcn:p,state:t.state,last:!0})]})]})}),t.cr_census_total!=null&&t.cr_census_total>0&&j.length>0&&e.jsx(Ve,{eyebrow:"Last Cost Report",title:"Census by Payer",aside:t.cr_census_fy_year?e.jsxs("span",{className:"font-mono text-[11px] text-muted-foreground",children:["FY ",t.cr_census_fy_year]}):null,children:e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5",children:[e.jsx("div",{className:"flex h-3 w-full overflow-hidden rounded-full bg-secondary",children:j.map(M=>e.jsx("div",{className:M.color,style:{width:`${M.count/t.cr_census_total*100}%`},title:`${M.key} ${(M.count/t.cr_census_total*100).toFixed(1)}%`},M.key))}),e.jsx("div",{className:"mt-5 grid grid-cols-1 gap-px overflow-hidden rounded-lg border border-border bg-border sm:grid-cols-3",children:j.map(M=>{const f=M.count/t.cr_census_total*100;return e.jsxs("div",{className:"bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:Qe("h-2.5 w-2.5 rounded-sm",M.color)}),e.jsx("span",{className:"text-[12px] font-medium text-muted-foreground",children:M.key})]}),e.jsxs("div",{className:"mt-2 font-mono text-2xl font-semibold tabular text-foreground",children:[f.toFixed(1),e.jsx("span",{className:"text-sm text-muted-foreground",children:"%"})]}),e.jsxs("div",{className:"mt-0.5 font-mono text-[11px] tabular text-muted-foreground",children:[Math.round(M.count).toLocaleString()," residents"]})]},M.key)})})]})}),(t.county_total_pop||t.ma_penetration!=null)&&e.jsxs("div",{className:"grid grid-cols-1 gap-10 lg:grid-cols-2 lg:gap-8",children:[t.county_total_pop?e.jsx(Ve,{eyebrow:"Catchment Area",title:`County Demographics â ${t.county_name}`,children:e.jsxs("div",{className:"grid grid-cols-2 gap-px overflow-hidden rounded-xl border border-border bg-border",children:[e.jsx(tt,{title:"Total Population",value:t.county_total_pop?.toLocaleString(),stateAvgRaw:t.state_avg_total_pop?.toLocaleString(),rank:t.county_rank_total_pop,total:t.state_county_count,onRankClick:()=>r("total_pop")}),e.jsx(tt,{title:"Pop. 65+",value:t.county_pop_65_plus?.toLocaleString(),pct:t.county_pct_65_plus,stateAvg:t.state_avg_pct_65_plus,rank:t.county_rank_pct_65,total:t.state_county_count,onRankClick:()=>r("pct_65_plus")}),e.jsx(tt,{title:"Pop. 85+",value:t.county_pop_85_plus?.toLocaleString(),stateAvgRaw:t.state_avg_pop_85_plus?.toLocaleString(),rank:t.county_rank_pop_85_plus,total:t.state_county_count,onRankClick:()=>r("pop_85_plus")}),e.jsx(tt,{title:"Median HHI",value:t.county_median_hhi?"$"+t.county_median_hhi.toLocaleString():null,stateAvgRaw:t.state_avg_median_hhi?"$"+t.state_avg_median_hhi.toLocaleString():null,rank:t.county_rank_median_hhi,total:t.state_county_count,onRankClick:()=>r("median_hhi")}),e.jsx(tt,{title:"Medicare Growth (YoY)",value:t.county_medicare_yoy_growth!=null?(t.county_medicare_yoy_growth>0?"+":"")+t.county_medicare_yoy_growth.toFixed(1)+"%":null,stateAvgRaw:t.state_avg_medicare_yoy_growth!=null?(t.state_avg_medicare_yoy_growth>0?"+":"")+t.state_avg_medicare_yoy_growth.toFixed(1)+"%":null,rank:t.county_rank_medicare_growth,total:t.county_medicare_growth_total,onRankClick:()=>o("medicare_growth"),onTrendClick:t.ssa?()=>c(!0):void 0}),e.jsx(tt,{title:"Poverty Rate",value:t.county_total_pop&&t.county_pop_below_poverty?(t.county_pop_below_poverty/t.county_total_pop*100).toFixed(1)+"%":null,stateAvgRaw:t.state_avg_poverty_rate!=null?t.state_avg_poverty_rate.toFixed(1)+"%":t.state_avg_pop_below_poverty&&t.state_avg_total_pop?(t.state_avg_pop_below_poverty/t.state_avg_total_pop*100).toFixed(1)+"%":null,rank:t.county_rank_poverty_rate??t.county_rank_below_poverty,total:t.state_county_count,onRankClick:()=>r("poverty_rate")})]})}):e.jsx("div",{}),t.ma_penetration!=null?e.jsxs(Ve,{eyebrow:`Referral Control${t.ma_report_date?` · ${t.ma_report_date}`:""}`,title:"Medicare Advantage",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-3",children:[e.jsx(zt,{title:"MA Penetration",value:t.ma_penetration.toFixed(1)+"%",sub:t.ma_rank_penetration!=null&&t.ma_state_county_count!=null?`#${t.ma_rank_penetration} of ${t.ma_state_county_count} in state`:void 0,onSubClick:t.ma_rank_penetration!=null?()=>
6o("ma_penetration"):void 0,subTitle:"See all counties in state ranked by MA penetration"}),e.jsx(zt,{title:"MA Enrolled",value:t.ma_county_enrolled?.toLocaleString(),sub:t.ma_rank_enrolled!=null&&t.ma_state_county_count!=null?`#${t.ma_rank_enrolled} of ${t.ma_state_county_count} in state`:void 0,onSubClick:t.ma_rank_enrolled!=null?()=>o("ma_enrolled"):void 0,subTitle:"See all counties in state ranked by MA enrollment"}),t.ma_top_plans?.length>0&&(()=>{const M=t.ma_top_plans[0],f=M.enrolled&&t.ma_county_enrolled?M.enrolled/t.ma_county_enrolled*100:null,w=t.ma_top_plan_share_rank;return e.jsx(zt,{title:"Top Plan Share",value:f!=null?f.toFixed(0)+"%":"â",sub:`${M.organization_marketing_name||M.contract_id}${w?` · #${w.rank}/${w.total}`:""}`,onSubClick:w?()=>o("top_plan_share"):void 0,subTitle:"See all counties in state ranked by top-plan share"})})()]}),t.ma_top_plans?.length>0&&e.jsxs("div",{className:"mt-4 overflow-hidden rounded-xl border border-border bg-card",children:[e.jsx("div",{className:"border-b border-border px-4 py-2.5 font-mono text-[11px] font-medium uppercase tracking-[0.14em] text-muted-foreground",children:"Top Plans"}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-border",children:[e.jsx("th",{scope:"col",className:"px-4 py-2 text-left font-mono text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Plan"}),e.jsx("th",{scope:"col",className:"px-4 py-2 text-right font-mono text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Enrolled"}),e.jsx("th",{scope:"col",className:"px-4 py-2 text-right font-mono text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Share"}),e.jsx("th",{scope:"col",className:"px-4 py-2 text-right font-mono text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"YoY"})]})}),e.jsx("tbody",{children:t.ma_top_plans.slice(0,5).map((M,f)=>{const w=M.enrolled&&t.ma_county_enrolled?M.enrolled/t.ma_county_enrolled*100:null,B=t.ma_top_plans[0]?.enrolled&&t.ma_county_enrolled?t.ma_top_plans[0].enrolled/t.ma_county_enrolled*100:null,z=M.enrolled!=null&&M.enrolled_prior_year!=null?M.enrolled-M.enrolled_prior_year:null,_=M.parent_organization||M.organization_marketing_name,S=_?`/ma?tab=${encodeURIComponent("Plan Explorer")}&org=${encodeURIComponent(_)}`:null;return e.jsxs("tr",{className:"border-b border-border last:border-b-0",children:[e.jsxs("td",{className:"px-4 py-2.5",children:[S?e.jsxs("a",{href:S,className:"font-medium text-foreground hover:underline",title:`View ${_} in MA Plan Explorer`,children:[M.organization_marketing_name??M.contract_id," ",e.jsx(pa,{size:11,className:"inline"})]}):e.jsx("span",{className:"font-medium text-foreground",children:M.organization_marketing_name??M.contract_id}),e.jsx("div",{className:"font-mono text-[11px] text-muted-foreground",children:M.plan_type})]}),e.jsx("td",{className:"px-4 py-2.5 text-right font-mono tabular text-foreground",children:M.enrolled?.toLocaleString()??"â"}),e.jsx("td",{className:"px-4 py-2.5 text-right",children:w!=null?e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx("div",{className:"hidden h-1.5 w-16 overflow-hidden rounded-full bg-secondary sm:block",children:e.jsx("div",{className:"h-full rounded-full bg-chart-1",style:{width:`${Math.min(100,B?w/B*100:0)}%`}})}),e.jsxs("span",{className:"font-mono tabular text-muted-foreground",children:[w.toFixed(1),"%"]})]}):e.jsx("span",{className:"font-mono tabular text-muted-foreground",children:"â"})}),e.jsx("td",{className:"px-4 py-2.5 text-right font-mono tabular",children:z!=null?e.jsxs("span",{className:z>0?"text-positive":z<0?"text-negative":"text-muted-foreground",children:[z>0?"+":"",z.toLocaleString()]}):e.jsx("span",{className:"text-muted-foreground",children:"â"})})]},f)})})]})]}),e.jsx(Sa,{ccn:t.ccn}),e.jsxs("a",{href:`/ma?state=${t.state}${t.ssa?`&county=${t.ssa}`:""}`,target:"_blank",rel:"noopener noreferrer",className:"mt-3 inline-flex items-center gap-1 font-mono text-[11px] font-medium text-primary hover:underline",children:["View MA trends for ",t.county_name||t.state," ",e.jsx(gt,{size:13})]})]}):e.jsx("div",{})]}),e.jsx(Ve,{eyebrow:"Facility Attributes",title:"Classification",children:e.jsx("div",{className:"grid grid-cols-2 gap-px overflow-hidden rounded-xl border border-border bg-border sm:grid-cols-3 lg:grid-cols-5",children:L.map(([M,f],w)=>e.jsxs("div",{className:"bg-card p-3",children:[e.jsx("div",{className:"font-mono text-[10px] uppercase tracking-wide text-muted-foreground",children:M}),e.jsx("div",{className:"mt-1 text-sm",children:f})]},w))})})]})]})}const $a=[{key:"Overview",tip:"Your starting point for understanding this facility. Displays CMS Five-Star ratings, certified beds, average daily census, occupancy, and staffing hours. Additional columns are available including health inspection rating, QM rating, RN hours, fines, and more. Use this tab to get oriented, then select any of the other tabs to dive deeper into specific areas of the facility's performance."},{key:"Trends",tip:"See how this facility's key metrics have changed over time. Tracks star ratings, occupancy, staffing hours, and turnover across monthly CMS snapshots. Use this to identify whether a facility is on an upward or downward trajectory before diving into the details of why."},{key:"Workforce",tip:"Understand the workforce at this facility. The CMS staffing star scorecard breaks down the Five-Star staffing rating; the staffing detail shows leadership and department tenure, agency reliance by role, and a visual timeline of administrator and DON tenure from PBJ data. High agency usage or frequent leadership turnover are early warning signs of operational challenges."},{key:"Competitors",tip:"Compare this facility against SNFs within 15 miles, ranked by SNF InsightScore. If fewer than 10 fall inside that radius it widens to reach the nearest 10, and the header states the distance actually used. The arrow on any score opens the full domain-by-domain breakdown against your facility. Use the Columns button to add turnover, agency reliance, leadership tenure, fines, quality measures, and cost report metrics."},{key:"Commercial Rates",minTier:"professional",tip:"View payer-negotiated rates from Transparency in Coverage (TIC) machine-readable files. Compare this facility's contracted rates against state and market peers by billing code and payer. Rates are sourced from published payer files and may not reflect current contract terms. This is one of the most unique datasets on the platform."},{key:"Financial",tip:"Deep financial analysis from CMS cost reports (HCRIS Form 2540-10). Includes net revenue, operating income, EBITDAR, payer mix by patient days, department cost per day, and staffing hourly rates with contract/salary splits. All metrics are benchmarked against state peers with percentile rankings. Select different fiscal years to track financial performance over time."},{key:"Quality & MDS",tip:"Four sub-tabs: QM Star Scorecard breaks down the CMS Five-Star quality rating with state rankings. Clinical Acuity compares resident complexity via PDPM comorbidity prevalence. Quality Outcomes shows QRP measures (rehospital
6ization, ED visits, function scores). MDS Clinical Detail explores individual assessment items by category with trends and state comparisons."},{key:"Deficiencies",tip:"Review this facility's health inspection survey history plus a built-in Mock Survey Prep generator (Professional tier). Each citation shows deficiency tag, scope/severity code (A through L), correction status, and survey date. Use Mock Survey Prep to generate a prioritized walk-through list of F-tags this facility is most likely to be cited on at its next state survey â blends own citation history, state cohort trends, and regional surveyor focus."},{key:"Job Postings",tip:"Active job listings matched to this facility from national job boards. See open positions, salary ranges, and sign-on bonus offers. High posting volume or persistent openings can indicate staffing challenges. Salary data helps benchmark compensation against market rates for the same roles."}],co=$a.map(t=>t.key),Ds=["0101","0110","0120","0130","0191","0192","0193","0194"],xo=["92523","97116","97162","97530"],mo=1e3,Ts={operator:0,business_office_manager:1,professional:2,enterprise:3};function xc(){const{ccn:t}=fn(),s=Us(),{user:a}=qs(),[n,r]=Js(),l=n.get("tab"),[o,d]=b.useState(l&&co.includes(l)?l:"Overview"),[c,m]=b.useState(null),p=n.get("overview"),[i,h]=b.useTransition(),v=R=>{r(V=>{const X=new URLSearchParams(V);return R==="Overview"?X.delete("tab"):X.set("tab",R),X.delete("subtab"),X},{replace:!0}),h(()=>d(R))},y=Ts[a?.tier]??0,L=$a.filter(R=>!R.minTier||y>=Ts[R.minTier]),[D,j]=b.useState(!1),[M,f]=b.useState(!1),w=o==="Overview"&&p==="v2",[B,z]=b.useState(!1),_=b.useMemo(()=>gn(t),[t]),S=R=>{const V=new URLSearchParams(n);window.location.href=`/facility/${R}${V.toString()?"?"+V.toString():""}`},C=n.get("from")==="market",u=n.get("market_ccn"),g=n.get("radius"),{data:A,isLoading:x,isError:P,error:$}=ee({queryKey:["facility",t],queryFn:()=>kn(t)}),{data:T}=ee({queryKey:["facility-address-history",t],queryFn:()=>Sn(t),enabled:!!t,staleTime:600*1e3}),{data:F}=ee({queryKey:["facility-ownership",t],queryFn:()=>Cn(t),enabled:!!t,staleTime:600*1e3});return x?e.jsx(Te,{text:"Loading facility..."}):P?e.jsx(_a,{msg:$.message}):e.jsxs("div",{className:"p-3 md:p-6 max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[C?e.jsxs("button",{onClick:()=>s(`/market?ccn=${u||t}${g?`&radius=${g}`:""}`),className:"flex items-center gap-1 text-sm text-sky-600 hover:text-sky-800 font-medium",children:[e.jsx(Kt,{size:14})," ",e.jsx(Xs,{size:14,className:"ml-0.5"})," Back to Market Analysis"]}):e.jsxs("button",{onClick:()=>s("/"),className:"flex items-center gap-1 text-sm text-slate-500 hover:text-slate-800",children:[e.jsx(Kt,{size:14})," Back to search"]}),e.jsx(ho,{ccn:t,navigate:s,fromMarket:C})]}),A.is_inactive&&e.jsxs("div",{className:"mb-4 rounded border border-amber-200 bg-amber-50 px-3 py-2 flex items-start gap-2",children:[e.jsx(Xt,{size:14,className:"text-amber-700 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 text-xs text-amber-900",children:[e.jsx("span",{className:"font-semibold",children:"Inactive â "}),"this facility was last in the CMS roster on ",e.jsx("span",{className:"font-semibold",children:A.last_seen}),". All data below is frozen as of that snapshot. Likely closure",A.closure_confidence?` (${A.closure_confidence.toLowerCase()} confidence)`:"",", but data lag or re-listing remain possible."]})]}),e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[_.prev&&e.jsx("button",{onClick:()=>S(_.prev),title:"Previous facility",className:"p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors",children:e.jsx(Gr,{size:20})}),e.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:A.provider_name}),_.next&&e.jsx("button",{onClick:()=>S(_.next),title:"Next facility",className:"p-1 rounded hover:bg-slate-100 text-slate-400 hover:text-slate-700 transition-colors",children:e.jsx(gt,{size:20})}),e.jsx(yn,{ccn:t,size:18}),e.jsx(Ln,{entityType:"facility",entityId:t,entityName:A.provider_name,fields:[{key:"provider_name",label:"Facility Name",currentValue:A.provider_name},{key:"provider_address",label:"Address",currentValue:A.provider_address},{key:"citytown",label:"City",currentValue:A.citytown},{key:"telephone_number",label:"Phone",currentValue:A.telephone_number},{key:"ownership_type",label:"Ownership Type",currentValue:A.ownership_type},{key:"chain_name",label:"Chain / Management Company",currentValue:A.chain_name},{key:"bed_count",label:"Certified Beds",currentValue:A.number_of_certified_beds},{key:"other",label:"Other",currentValue:""}]}),e.jsx(On,{type:"facility",id:t})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-2",children:[A.chain_name&&A.chain_id&&e.jsxs(lt,{to:`/chain/${A.chain_id}`,className:"inline-flex items-center gap-1 text-xs bg-slate-100 hover:bg-sky-50 hover:text-sky-700 text-slate-600 px-2 py-0.5 rounded-full border border-slate-200 transition-colors",children:[e.jsx(bn,{size:11})," ",A.chain_name," · ",A.number_of_facilities_in_chain," facilities"]}),a&&e.jsxs("button",{onClick:()=>f(!0),className:"inline-flex items-center gap-1 text-xs bg-slate-100 hover:bg-sky-50 hover:text-sky-700 text-slate-600 px-2 py-0.5 rounded-full border border-slate-200 transition-colors",title:"Ownership / operator lineage (cost-report A-8-1, 1995âpresent)",children:[e.jsx(_n,{size:11})," Lineage"]}),a&&e.jsx(po,{data:F})]}),e.jsx("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 mt-2 text-sm text-slate-500",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(jn,{size:13}),A.provider_address,", ",A.citytown,", ",A.state," ",A.zip_code,T?.latest_move&&!T.latest_move.likely_reformat&&T.n_address_spans>1&&e.jsx(uo,{history:T})]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 mt-1 text-xs text-slate-400",children:[A.ownership_type&&e.jsx("span",{children:A.ownership_type}),(A.special_focus_status==="SFF"||A.special_focus_status==="SFF Candidate")&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),A.special_focus_status==="SFF"?e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-red-100 text-red-700 font-semibold text-[10px] uppercase",title:"CMS Special Focus Facility â a documented history of serious quality problems, with more frequent surveys.",children:"Special Focus Facility"}):e.jsx("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold text-[10px] uppercase",title:"CMS SFF Candidate â identified as eligible for Special Focus Facility selection. NOT currently in the SFF program.",children:"SFF Candidate"})]}),o==="Overview"&&A.snapshot_date&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx(vn,{label:"CMS data as of",date:A.snapshot_date})]}),w&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{className:"font-mono font-medium text-slate-600",children:["CCN ",t]}),A.npi&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsxs("span",{className:"font-mono text-slate-500",children:["NPI ",A.npi]})]})]})]})]}),w?e.jsx("div",{className:"shrink-0",children:e.jsx(lo,{f:A,onShowHistory:()=>z(!0),onShowCompetitors:()=>v("Competitors")})}):e.jsxs("div",{className:"text-right shrink-0",children:[e.jsx("p",{className:"font-mono font-semibold text-slate-700",children:t}),A.npi&&e.jsxs("p",{className:"text-[10px] text-slate-400 mt-0.5 font-mono",children:["NPI ",A.npi]})]})]}),e.jsxs("div",{className:`flex flex-wrap gap-x-0.5 gap-y-1 border-b border-slate-200 mb-4 md:mb-6 mt-4 relative ${i?"opacity-70":""}`,children:[L.map(({key:R,tip:V})=>e.jsxs("button",{onClick:()=>v(R),disabled:i&&o!==R,className:`px-3 md:px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap transition-colors -mb-px flex items-center gap-1 ${o===R?"border-sky-500 text-sky-600":"border-transparent text-slate-500 hover:text-slate-800"}`,children:[R,V&&e.jsx(le,{text:V,size:10,position:"below",portal:!0})]},R)),i&&e.jsxs("span",{className:"absolute right-0 top-1/2 -translate-y-1/2 text-[11px] text-slate-400 flex items-center gap-1",children:[e.jsx(ge,{size:11,className:"animate-spin"})," switchingâ¦"]})]}),e.jsxs(Ao,{children:[o==="Overview"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-end gap-1.5 mb-3",children:[e.jsx("span",{className:"text-[11px] text-slate-400 mr-1",children:"Overview"}),e.jsx("button",{type:"button",onClick:()=>r(R=>{const V=new URLSearchParams(R);return V.delete("overview"),V},{replace:!0}),className:`text-[11px] font-medium px-2.5 py-0.5 rounded-full border transition-colors ${p==="v2"?"border-slate-200 text-slate-500 hover:bg-slate-50":"border-sky-300 bg-sky-50 text-sky-700"}`,children:"Classic"}),e.jsx("button",{type:"button",onClick:()=>r(R=>{const V=new URLSearchParams(R);return V.set("overview","v2"),V},{replace:!0}),className:`text-[11px] font-medium px-2.5 py-0.5 rounded-full border transition-colors ${p==="v2"?"border-sky-300 bg-sky-50 text-sky-700":"border-slate-200 text-slate-500 hover:bg-slate-50"}`,children:"New (beta)"})]}),p==="v2"?e.jsx(oo,{f:A,onShowCompetitors:()=>v("Competitors"),onDrillToTrends:R=>{m(R),v("Trends")}}):e.jsx(ro,{f:A,onShowCompetitors:()=>v("Competitors"),onDrillToTrends:R=>{m(R),v("Trends")}}),e.jsx(qr,{onRequestClick:()=>j(!0),context:"facility"})]}
6),o==="Trends"&&e.jsx(go,{ccn:t,facility:A,focusKey:c,onFocusConsumed:()=>m(null)}),o==="Workforce"&&e.jsx(fi,{ccn:t,facility:A}),o==="Competitors"&&e.jsx(Co,{ccn:t,facility:A,navigate:s}),o==="Commercial Rates"&&e.jsx(Mo,{ccn:t,facility:A}),o==="Financial"&&e.jsx(Di,{ccn:t}),o==="Quality & MDS"&&e.jsx(Bi,{ccn:t,facility:A,initialSubTab:n.get("subtab")}),o==="Deficiencies"&&e.jsx(Xi,{ccn:t,facility:A}),o==="Job Postings"&&e.jsx(Fo,{ccn:t,facility:A})]},o),e.jsx(Hr,{isOpen:D,onClose:()=>j(!1),pageContext:"facility"}),M&&e.jsx(En,{mode:"facility",ccn:t,title:`${A.provider_name||t}${A.citytown?` · ${A.citytown}, ${A.state}`:""}`,onClose:()=>f(!1)}),B&&e.jsx(va,{ccn:t,facilityName:A.provider_name||t,onClose:()=>z(!1)})]})}function uo({history:t}){const[s,a]=b.useState(!1),[n,r]=b.useState(null),l=b.useRef(null),o=b.useRef(null);b.useEffect(()=>{if(!s)return;const i=v=>{o.current&&o.current.contains(v.target)||l.current&&l.current.contains(v.target)||a(!1)},h=v=>{o.current&&o.current.contains(v.target)||a(!1)};return document.addEventListener("mousedown",i),window.addEventListener("scroll",h,!0),()=>{document.removeEventListener("mousedown",i),window.removeEventListener("scroll",h,!0)}},[s]);const d=t?.latest_move,c=t?.spans||[];if(!d)return null;const m=i=>{if(i.stopPropagation(),s){a(!1);return}const h=l.current?.getBoundingClientRect();if(!h)return;const v=320,y=Math.min(280,80+c.length*56);let L=h.left-6,D=h.bottom+6;L+v>window.innerWidth-8&&(L=Math.max(8,window.innerWidth-v-8)),D+y>window.innerHeight-8&&(D=Math.max(8,h.top-y-6)),r({top:D,left:L}),a(!0)},p=`Moved ${d.move_in_snapshot} from ${d.prior_address}, ${d.prior_city}${d.miles_moved!=null?` (~${d.miles_moved.toFixed(1)} mi)`:""}. Click for full history.`;return e.jsxs(e.Fragment,{children:[e.jsx("button",{ref:l,onClick:m,title:p,"aria-label":"View address history",className:"ml-1 inline-flex items-center justify-center w-5 h-5 rounded-full text-amber-600 hover:text-amber-700 hover:bg-amber-50 transition-colors cursor-pointer",children:e.jsx(nl,{size:13})}),s&&n&&Zt.createPortal(e.jsxs("div",{ref:o,className:"fixed bg-white border border-slate-200 rounded-lg shadow-2xl w-80 overflow-hidden",style:{top:n.top,left:n.left,zIndex:9999,maxHeight:360},children:[e.jsxs("div",{className:"px-3 py-2 border-b border-slate-100 bg-slate-50",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-700 uppercase tracking-wide",children:"Address History"}),e.jsxs("p",{className:"text-[11px] text-slate-500 mt-0.5",children:[t.n_address_spans," addresses on file",d.miles_moved!=null&&` · latest move ~${d.miles_moved.toFixed(1)} mi`]})]}),e.jsx("ol",{className:"divide-y divide-slate-100 overflow-y-auto",style:{maxHeight:280},children:[...c].reverse().map((i,h)=>{const v=h===0;return e.jsxs("li",{className:`px-3 py-2 ${v?"bg-emerald-50/30":""}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-medium uppercase tracking-wide mb-0.5",children:[v?e.jsx("span",{className:"text-emerald-700",children:"Current"}):e.jsx("span",{className:"text-slate-500",children:"Previous"}),e.jsxs("span",{className:"text-slate-400",children:[i.first_seen," â ",i.last_seen]})]}),e.jsx("div",{className:"text-xs text-slate-700",children:i.provider_address}),e.jsxs("div",{className:"text-[11px] text-slate-500",children:[i.citytown,", ",i.state," ",i.zip_code]})]},`${i.first_seen}-${i.provider_address}`)})})]}),document.body)]})}function po({data:t}){const[s,a]=b.useState(!1),[n,r]=b.useState(null),l=b.useRef(null),o=b.useRef(null);b.useEffect(()=>{if(!s)return;const j=f=>{o.current&&o.current.contains(f.target)||l.current&&l.current.contains(f.target)||a(!1)},M=f=>{o.current&&o.current.contains(f.target)||a(!1)};return document.addEventListener("mousedown",j),window.addEventListener("scroll",M,!0),()=>{document.removeEventListener("mousedown",j),window.removeEventListener("scroll",M,!0)}},[s]);const d=t?.owners||[];if(!d.length)return null;const c=j=>/OWNERSHIP INTEREST/.test((j.roles||"").toUpperCase()),m=j=>/INDIRECT OWNERSHIP/.test((j.roles||"").toUpperCase()),p=j=>/OPERATIONAL|MANAGERIAL|MANAGEMENT|ADP/.test((j.roles||"").toUpperCase()),i=d.filter(j=>c(j)&&!m(j)).sort((j,M)=>(M.pct||0)-(j.pct||0)),h=d.filter(j=>c(j)&&m(j)).sort((j,M)=>(M.pct||0)-(j.pct||0)),v=d.filter(j=>!c(j)&&p(j)),y=d.filter(j=>!c(j)&&!p(j)),L=({label:j,n:M})=>e.jsxs("div",{className:"px-3 py-1 bg-slate-50/70 border-y border-slate-100 text-[10px] font-semibold uppercase tracking-wide text-slate-400",children:[j," · ",M]}),D=j=>{if(j.stopPropagation(),s){a(!1);return}const M=l.current?.getBoundingClientRect();if(!M)return;const f=384,w=Math.min(400,96+d.length*40);let B=M.left-6,z=M.bottom+6;B+f>window.innerWidth-8&&(B=Math.max(8,window.innerWidth-f-8)),z+w>window.innerHeight-8&&(z=Math.max(8,M.top-w-6)),r({top:z,left:B}),a(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{ref:l,onClick:D,title:"Current legal ownership (CMS PECOS)",className:"inline-flex items-center gap-1 text-xs bg-slate-100 hover:bg-sky-50 hover:text-sky-700 text-slate-600 px-2 py-0.5 rounded-full border border-slate-200 transition-colors",children:[e.jsx(ll,{size:11})," Ownership"]}),s&&n&&Zt.createPortal(e.jsxs("div",{ref:o,className:"fixed bg-white border border-slate-200 rounded-lg shadow-2xl overflow-hidden",style:{to
6p:n.top,left:n.left,zIndex:9999,width:384,maxHeight:400},children:[e.jsxs("div",{className:"px-3 py-2 border-b border-slate-100 bg-slate-50",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-700 uppercase tracking-wide",children:"Ownership"}),e.jsxs("p",{className:"text-[11px] text-slate-500 mt-0.5",children:[d.length," owners / disclosed parties · source: CMS PECOS"]}),t.last_chow&&e.jsxs("p",{className:"text-[11px] text-slate-600 mt-1",children:[e.jsx("span",{className:"font-semibold",children:"Last change of ownership:"})," ",t.last_chow.effective_date,t.last_chow.seller?e.jsxs(e.Fragment,{children:[" â ",Ce(t.last_chow.buyer||"")," ",e.jsx("span",{className:"text-slate-400",children:"â"})," ",Ce(t.last_chow.seller)]}):null]})]}),e.jsxs("div",{className:"overflow-y-auto",style:{maxHeight:316},children:[i.length>0&&e.jsxs("div",{children:[e.jsx(L,{label:"Direct owners",n:i.length}),i.map((j,M)=>e.jsxs("div",{className:"px-3 py-1.5 border-b border-slate-50 last:border-0 flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs text-slate-700 font-medium",children:Ce(j.name)}),j.since&&e.jsxs("div",{className:"text-[10px] text-slate-400",children:["on record since ",j.since]})]}),j.pct!=null&&e.jsxs("span",{className:"text-[11px] text-slate-500 whitespace-nowrap tabular-nums",children:[j.pct,"%"]})]},M))]}),h.length>0&&e.jsxs("div",{children:[e.jsx(L,{label:"Indirect / upstream owners",n:h.length}),h.map((j,M)=>e.jsxs("div",{className:"px-3 py-1.5 border-b border-slate-50 last:border-0 flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("span",{className:"text-xs text-slate-700",children:Ce(j.name)}),j.since&&e.jsxs("div",{className:"text-[10px] text-slate-400",children:["on record since ",j.since]})]}),j.pct!=null&&e.jsxs("span",{className:"text-[11px] text-slate-500 whitespace-nowrap tabular-nums",children:[j.pct,"%"]})]},M)),e.jsx("p",{className:"px-3 py-1 text-[10px] text-slate-400 italic",children:"Each % is that owner's interest at its tier of the chain â upstream tiers don't total the facility."})]}),[["Operator & management",v],["Officers & directors",y]].map(([j,M])=>M.length>0&&e.jsxs("div",{children:[e.jsx(L,{label:j,n:M.length}),M.map((f,w)=>e.jsxs("div",{className:"px-3 py-1.5 border-b border-slate-50 last:border-0",children:[e.jsx("span",{className:"text-xs text-slate-700 font-medium",children:Ce(f.name)}),e.jsxs("div",{className:"text-[10px] text-slate-400 mt-0.5 flex items-center gap-1 flex-wrap",children:[f.roles&&e.jsx("span",{className:"uppercase tracking-tight",children:f.roles}),f.management_company&&e.jsx("span",{className:"px-1 rounded bg-slate-100 text-slate-500",children:"mgmt co"})]})]},w))]},j))]}),e.jsx("div",{className:"px-3 py-1.5 border-t border-slate-100 bg-slate-50 text-[10px] text-slate-400",children:"CMS PECOS ownership snapshot. Association dates omitted (enrollment-filing artifacts, not chain-join dates)."})]}),document.body)]})}function ho({ccn:t,navigate:s,fromMarket:a}){const[n,r]=b.useState(!1),l=b.useRef(null);return b.useEffect(()=>{const o=d=>{l.current&&!l.current.contains(d.target)&&r(!1)};return n&&document.addEventListener("mousedown",o),()=>document.removeEventListener("mousedown",o)},[n]),e.jsxs("div",{className:"relative",ref:l,children:[e.jsxs("button",{onClick:()=>r(!n),className:"flex items-center gap-1 px-3 py-1.5 text-xs text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg transition-colors font-medium",children:[e.jsx(el,{size:14})," Actions"]}),n&&e.jsxs("div",{className:"absolute right-0 top-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg py-1 z-50 min-w-[200px]",children:[!a&&e.jsxs("a",{href:`/market?ccn=${t}`,target:"_blank",rel:"noopener noreferrer",onClick:()=>r(!1),className:"flex items-center gap-2 px-3 py-2 text-xs text-slate-700 hover:bg-slate-50",children:[e.jsx(Xs,{size:13,className:"text-emerald-500"})," View Market Map"]}),e.jsxs("button",{onClick:()=>{r(!1),s(`/facilities/compare?ccns=${t}`)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-slate-700 hover:bg-slate-50 text-left",children:[e.jsx(ea,{size:13,className:"text-sky-500"})," Compare with other SNFs"]}),e.jsxs("a",{href:`/facility/${t}/report`,target:"_blank",rel:"noopener noreferrer",onClick:()=>r(!1),className:"flex items-center gap-2 px-3 py-2 text-xs text-slate-700 hover:bg-slate-50",children:[e.jsx(Ue,{size:13,className:"text-slate-500"})," Print Report"]}),e.jsxs("a",{href:`/genome?ccn=${t}`,target:"_blank",rel:"noopener noreferrer",onClick:()=>r(!1),className:"flex items-center gap-2 px-3 py-2 text-xs text-slate-700 hover:bg-slate-50",children:[e.jsx(Jt,{size:13,className:"text-slate-400"})," Find Similar Facilities"]})]})]})}const mt=[{key:"Overall",field:"overall_rating",color:"#0ea5e9"},{key:"Health",field:"health_inspection_rating",color:"#f97316"},{key:"Staffing",field:"staffing_rating",color:"#10b981"},{key:"QM",field:"qm_rating",color:"#8b5cf6"},{key:"Long Stay QM",field:"longstay_qm_rating",color:"#ec4899"},{key:"Short Stay QM",field:"shortstay_qm_rating",color:"#4f46e5"}],Bt=.45;function fo({active:t,payload:s,label:a}){if(!t||!s?.length)return null;const n=s[0]?.payload||{},r=s.filter(l=>l.dataKey!=="SFF"&&l.dataKey!=="CAND"&&l.value!=null);return e.jsxs("div",{className:"bg-white border border-slate-200 rounded-md shadow px-2.5 py-1.5 text-xs",children:[e.jsx("div",{className:"font-medium text-slate-600 mb-0.5",children:a}),n._sff&&e.jsx("div",{className:"text-red-600 font-medium",children:"Special Focus â no CMS rating"}),n._cand&&e.jsx("div",{className:"text-amber-600 font-medium",children:"SFF Candidate"}),!n._sff&&r.map(l=>e.jsxs("div",{style:{color:l.color},children:[l.name,": ",l.value]},l.dataKey))]})}function go({ccn:t,facility:s,focusKey:a,onFocusConsumed:n}){const[r,l]=b.useState(()=>new Set([a||"Overall"])),[o,d]=b.useState([0,100]),[c,m]=b.useState("state"),[p,i]=b.useState(null),[h,v]=b.useState(!0),y=b.useCallback(()=>i(null),[]),L=De(y);b.useEffect(()=>{a&&(l(new Set([a])),v(!0),n?.())},[a]);const{data:D,isLoading:j,isError:M,error:f}=ee({queryKey:["facility-ratings",t],queryFn:()=>Mn(t),enabled:!!t}),w=D?.results??[],B=b.useMemo(()=>w.some(I=>I.special_focus_status==="SFF"),[w]),z=b.useMemo(()=>w.some(I=>I.special_focus_status==="SFF Candidate"),[w]),_=b.useMemo(()=>
6{const I=[...w].reverse(),E=mt.find(te=>r.has(te.key)),W=te=>te?.special_focus_status;return I.map((te,me)=>{const Se=W(te)==="SFF",ve=W(te)==="SFF Candidate",ot=W(I[me-1])==="SFF"||W(I[me+1])==="SFF",Le=W(I[me-1])==="SFF Candidate"||W(I[me+1])==="SFF Candidate",He={date:te.snapshot_date?.slice(0,7),_sff:Se,_cand:ve};for(const ct of mt)r.has(ct.key)&&(He[ct.key]=Se?null:Ne(te[ct.field]));const Ke=E?Ne(te[E.field]):null;return He.SFF=Se?Bt:ot&&E?Ke:null,He.CAND=ve||Le?Ke:null,He})},[w,r]),S=b.useMemo(()=>{const I=[];let E=null,W=null;for(const te of[...w].reverse()){const me=te.snapshot_date?.slice(0,7);te.special_focus_status==="SFF"?(E===null&&(E=me),W=me):E!==null&&(I.push([E,W]),E=null)}return E!==null&&I.push([E,W]),I},[w]),C=b.useMemo(()=>{const I=c==="nearest"?D?.nearest_10_averages??[]:D?.state_averages??[],E={};for(const W of I)E[W.snapshot_date?.slice(0,7)]=W;return E},[D,c]),u=b.useMemo(()=>kt(w,I=>{const E=Ne(I.number_of_certified_beds),W=Ne(I.average_number_of_residents_per_day),te=E>0&&W>0?Math.round(W/E*1e3)/10:null,me=C[I.snapshot_date?.slice(0,7)];return{"Occupancy %":te,"State Median":me?.avg_occupancy_pct??null,ADC:W>0?W:null}}),[w,C]),g=b.useMemo(()=>kt(w,I=>{const E=C[I.snapshot_date?.slice(0,7)];return{"RN HPRD":Ne(I.reported_rn_hprd),"Total Nurse HPRD":Ne(I.reported_total_nurse_hprd),"State RN Median":E?.avg_rn_hprd??null,"State Total Median":E?.avg_total_nurse_hprd??null}}).filter(I=>I.date>="2018-04"),[w,C]),A=b.useMemo(()=>kt(w,I=>{const E=C[I.snapshot_date?.slice(0,7)];return{"Direct Care Turnover %":Ne(I.total_nursing_staff_turnover),"State Median":E?.avg_turnover??null}}).filter(I=>I.date>="2022-01"),[w,C]),x=b.useMemo(()=>kt(w,I=>{const E=C[I.snapshot_date?.slice(0,7)];return{"Case Mix Index":Ne(I.nursing_casemix_index_ratio??null),"State Median":E?.avg_casemix??null}}).filter(I=>I.date>="2024-07"),[w,C]),{data:P}=ee({queryKey:["quality-trend",t],queryFn:()=>$n(t),enabled:!!t}),$=b.useMemo(()=>(P?.results??[]).map(I=>({date:I.date,"Short-Stay Rehosp %":I.ss_rehosp,"State Median":c==="nearest"?I.nearest_ss_rehosp:I.state_ss_rehosp})),[P,c]),T=b.useMemo(()=>(P?.results??[]).map(I=>({date:I.date,"Hosp / 1,000 Days":I.ls_hosp,"State Median":c==="nearest"?I.nearest_ls_hosp:I.state_ls_hosp})),[P,c]),F=b.useMemo(()=>{const I={};for(const E of P?.results??[])I[E.date]=E;return I},[P]),R=b.useMemo(()=>[...w].reverse(),[w]),V=R.length,X=Math.floor(o[0]/100*V),O=Math.max(X+1,Math.ceil(o[1]/100*V)),G=R.slice(X,O),J=G[0]?.snapshot_date?.slice(0,7),Z=G[G.length-1]?.snapshot_date?.slice(0,7),se=I=>I.filter(E=>(!J||E.date>=J)&&(!Z||E.date<=Z)),N=I=>{l(E=>{const W=new Set(E);return W.has(I)?W.delete(I):W.add(I),W})};if(j)return e.jsx(Te,{});if(M)return e.jsx(_a,{msg:f?.message||"Failed to load trend data."});const Y=s?.state||"",U=c==="nearest"?"Nearest 10":"State median",H=c==="nearest"?"nearest-10 median":Y?`${Y} state median`:"state median",ae=I=>e.jsxs($e,{data:se(_),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:I>300?12:11}}),e.jsx(xe,{domain:[0,5],ticks:B?[Bt,1,2,3,4,5]:[1,2,3,4,5],tickFormatter:E=>E===Bt?"SFF":E,tick:{fontSize:11}}),S.map(([E,W],te)=>{const me=J&&E<J?J:E,Se=Z&&W>Z?Z:W;return Z&&me>Z||J&&Se<J?null:e.jsx(Ur,{x1:me,x2:Se,y1:0,y2:.82,fill:"#ef4444",fillOpacity:.14},te)}),e.jsx(ce,{content:e.jsx(fo,{})}),mt.filter(E=>r.has(E.key)).map(E=>e.jsx(oe,{type:"monotone",dataKey:E.key,stroke:E.color,strokeWidth:2,dot:!1},E.key)),B&&e.jsx(oe,{type:"monotone",dataKey:"SFF",stroke:"#dc2626",strokeWidth:2.5,dot:!1,connectNulls:!1}),z&&e.jsx(oe,{type:"monotone",dataKey:"CAND",stroke:"#f59e0b",strokeWidth:2.5,dot:!1,connectNulls:!1})]});return e.jsxs("div",{className:"space-y-6",children:[V>1&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-slate-400 mb-1",children:[e.jsx("span",{children:J}),e.jsxs("span",{className:"text-slate-500 font-medium",children:[G.length," of ",V," months"]}),e.jsx("span",{children:Z})]}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"range",min:0,max:100,value:o[0],onChange:I=>d([Math.min(Number(I.target.value),o[1]-5),o[1]]),className:"flex-1 accent-sky-500 h-1.5"}),e.jsx("input",{type:"range",min:0,max:100,value:o[1],onChange:I=>d([o[0],Math.max(Number(I.target.value),o[0]+5)]),className:"flex-1 accent-sky-500 h-1.5"})]})]}),p&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-3 md:p-6",onClick:()=>i(null),children:e.jsxs("div",{ref:L,role:"dialog","aria-modal":"true","aria-labelledby":"trends-expanded-title",className:"bg-white rounded-lg shadow-lg w-full max-w-5xl p-4 md:p-6 relative",onClick:I=>I.stopPropagation(),children:[e.jsx("button",{onClick:()=>i(null),"aria-label":"Close chart",className:"absolute top-3 right-3 text-slate-400 hover:text-slate-700",children:e.jsx(xa,{size:18})}),e.jsx("h3",{id:"trends-expanded-title",className:"text-sm font-semibold text-slate-700 mb-1",children:p.title}),p.sub&&e.jsx("p",{className:"text-xs text-slate-400 mb-3",children:p.sub}),p.toggles&&e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:mt.map(I=>e.jsx("button",{onClick:()=>N(I.key),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-colors ${r.has(I.key)?"text-white border-transparent":"text-slate-400 border-slate-200 bg-white"}`,style:r.has(I.key)?{backgroundColor:I.color}:{},children:I.key},I.key))}),e.jsx(je,{width:"100%",height:450,children:p.chart})]})}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm",children:[e.jsxs("button",{onClick:()=>v(I=>!I),className:"w-full flex items-center justify-between p-5 text-left",children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700",children:"Star Rating Trends"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{onClick:I=>{I.stopPropagation(),i({title:"Star Rating Trends",toggles:!0,chart:
6ae(450)})},className:"text-slate-300 hover:text-slate-600 transition-colors p-1",title:"Expand chart",children:e.jsx(ft,{size:14})}),h?e.jsx(Ae,{size:16,className:"text-slate-400"}):e.jsx(ye,{size:16,className:"text-slate-400"})]})]}),h&&e.jsxs("div",{className:"px-5 pb-5",children:[e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:mt.map(I=>e.jsx("button",{onClick:()=>N(I.key),className:`px-2.5 py-1 rounded-full text-xs font-medium border transition-colors ${r.has(I.key)?"text-white border-transparent":"text-slate-400 border-slate-200 bg-white"}`,style:r.has(I.key)?{backgroundColor:I.color}:{},children:I.key},I.key))}),e.jsx(je,{width:"100%",height:280,children:ae(280)})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-slate-500",children:"Compare vs"}),e.jsx("div",{className:"inline-flex items-center bg-white border border-slate-200 rounded-lg p-0.5",children:[["state",Y?`${Y} state median`:"State median"],["nearest","Nearest 10"]].map(([I,E])=>e.jsx("button",{onClick:()=>m(I),className:`px-3 py-1 text-xs font-medium rounded-md transition-colors ${c===I?"bg-sky-600 text-white":"text-slate-500 hover:text-slate-700"}`,children:E},I))}),e.jsx("span",{className:"text-[11px] text-slate-400 italic",children:"Nearest 10 = the 10 closest competitors (any operator)"})]}),(()=>{const I=[{key:"occ",title:"Occupancy %",sub:`Gray dashed = ${H}`,chart:E=>e.jsxs($e,{data:se(u),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:E>300?11:10}}),e.jsx(xe,{domain:["auto","auto"],tick:{fontSize:10},tickFormatter:W=>W+"%"}),e.jsx(ce,{content:({active:W,payload:te,label:me})=>{if(!W||!te?.length)return null;const Se=te[0]?.payload?.ADC;return e.jsxs("div",{className:"rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-xs shadow-sm",children:[e.jsx("div",{className:"mb-0.5 font-medium text-slate-500",children:me}),te.filter(ve=>ve.value!=null).map(ve=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-sm",style:{background:ve.color}}),e.jsx("span",{className:"text-slate-600",children:ve.name}),e.jsxs("span",{className:"ml-auto font-medium text-slate-800 tabular-nums",children:[ve.value,"%"]})]},ve.name)),Se!=null&&e.jsxs("div",{className:"mt-1 pt-1 border-t border-slate-100 flex items-center gap-2 text-slate-500",children:[e.jsx("span",{children:"ADC"}),e.jsx("span",{className:"ml-auto font-medium text-slate-700 tabular-nums",children:Se.toFixed(1)})]})]})}}),e.jsx(Fe,{}),e.jsx(oe,{type:"monotone",dataKey:"Occupancy %",stroke:"#0ea5e9",strokeWidth:2,dot:!1,connectNulls:!0}),e.jsx(oe,{type:"monotone",dataKey:"State Median",name:U,stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"6 3",dot:!1,connectNulls:!0})]})},{key:"hprd",title:"Nursing Hours per Resident per Day",sub:`Dashed = ${H}`,chart:E=>e.jsxs($e,{data:se(g),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:E>300?11:10}}),e.jsx(xe,{domain:["auto","auto"],tick:{fontSize:10}}),e.jsx(ce,{}),e.jsx(Fe,{}),e.jsx(oe,{type:"monotone",dataKey:"Total Nurse HPRD",stroke:"#0ea5e9",strokeWidth:2,dot:!1,connectNulls:!0}),e.jsx(oe,{type:"monotone",dataKey:"State Total Median",name:U,stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"6 3",dot:!1,connectNulls:!0})]})},{key:"turnover",title:"Nursing Staff Turnover (%)",sub:`Gray dashed = ${H}`,chart:E=>e.jsxs($e,{data:se(A),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:E>300?11:10}}),e.jsx(xe,{domain:["auto","auto"],tick:{fontSize:10},tickFormatter:W=>W+"%"}),e.jsx(ce,{formatter:W=>W!=null?W+"%":"â"}),e.jsx(Fe,{}),e.jsx(oe,{type:"monotone",dataKey:"Direct Care Turnover %",stroke:"#f97316",strokeWidth:2,dot:!1,connectNulls:!0}),e.jsx(oe,{type:"monotone",dataKey:"State Median",name:U,stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"6 3",dot:!1,connectNulls:!0})]})},{key:"casemix",title:"Case Mix Index",sub:`Gray dashed = ${H}`,chart:E=>e.jsxs($e,{data:se(x),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:E>300?11:10}}),e.jsx(xe,{domain:["auto","auto"],tick:{fontSize:10}}),e.jsx(ce,{}),e.jsx(Fe,{}),e.jsx(oe,{type:"monotone",dataKey:"Case Mix Index",stroke:"#06b6d4",strokeWidth:2,dot:!1,connectNulls:!0}
6),e.jsx(oe,{type:"monotone",dataKey:"State Median",name:U,stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"6 3",dot:!1,connectNulls:!0})]})},{key:"ss_rehosp",title:"Short-Stay Rehospitalization (%)",sub:`Lower is better · Gray dashed = ${H}`,chart:E=>e.jsxs($e,{data:se($),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:E>300?11:10}}),e.jsx(xe,{domain:["auto","auto"],tick:{fontSize:10},tickFormatter:W=>W+"%"}),e.jsx(ce,{formatter:W=>W!=null?W+"%":"â"}),e.jsx(Fe,{}),e.jsx(oe,{type:"monotone",dataKey:"Short-Stay Rehosp %",stroke:"#f87171",strokeWidth:2,dot:!1,connectNulls:!0}),e.jsx(oe,{type:"monotone",dataKey:"State Median",name:U,stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"6 3",dot:!1,connectNulls:!0})]})},{key:"ls_hosp",title:"Long-Stay Hospitalizations (per 1,000 resident-days)",sub:`Lower is better · Gray dashed = ${H}`,chart:E=>e.jsxs($e,{data:se(T),children:[e.jsx(he,{strokeDasharray:"3 3",stroke:"#f1f5f9"}),e.jsx(de,{dataKey:"date",tick:{fontSize:E>300?11:10}}),e.jsx(xe,{domain:["auto","auto"],tick:{fontSize:10}}),e.jsx(ce,{}),e.jsx(Fe,{}),e.jsx(oe,{type:"monotone",dataKey:"Hosp / 1,000 Days",stroke:"#f87171",strokeWidth:2,dot:!1,connectNulls:!0}),e.jsx(oe,{type:"monotone",dataKey:"State Median",name:U,stroke:"#94a3b8",strokeWidth:1.5,strokeDasharray:"6 3",dot:!1,connectNulls:!0})]})}];return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:I.map(E=>e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-5 relative",children:[e.jsxs("div",{className:"flex items-start justify-between mb-0.5",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold text-slate-700",children:E.title}),E.sub&&e.jsx("p",{className:"text-xs text-slate-400",children:E.sub})]}),e.jsx("button",{onClick:()=>i({title:E.title,sub:E.sub,chart:E.chart(450)}),className:"text-slate-300 hover:text-slate-600 transition-colors p-1",title:"Expand chart",children:e.jsx(ft,{size:14})})]}),e.jsx("div",{className:"mt-3",children:e.jsx(je,{width:"100%",height:220,children:E.chart(220)})})]},E.key))})})(),e.jsx(yo,{slicedResults:G,stateAvgMap:C,qtMap:F,ccn:t})]})}function yo({slicedResults:t,stateAvgMap:s,qtMap:a={},ccn:n}){const[r,l]=b.useState(!1),o=b.useMemo(()=>[...t].reverse(),[t]),d=r?o:o.slice(0,24),c=o.length>24;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-slate-100",children:[e.jsxs("p",{className:"text-xs font-semibold text-slate-600 uppercase tracking-wide",children:["Trend Data (",d.length,c&&!r?` of ${o.length}`:""," rows)"]}),e.jsxs("button",{onClick:()=>{const m=t.map(p=>{const i=Ne(p.number_of_certified_beds),h=Ne(p.average_number_of_residents_per_day),v=i>0&&h>0?(h/i*100).toFixed(1):"",y=s[p.snapshot_date?.slice(0,7)]||{},L=a[p.snapshot_date?.slice(0,7)]||{};return{Date:p.snapshot_date?.slice(0,10),Overall:p.overall_rating??"",Health:p.health_inspection_rating??"",Staffing:p.staffing_rating??"",QM:p.qm_rating??"",Beds:p.number_of_certified_beds??"",ADC:p.average_number_of_residents_per_day??"","Occupancy %":v,"State Median Occ %":y.avg_occupancy_pct??"","RN HPRD":p.reported_rn_hprd??"","State Median RN HPRD":y.avg_rn_hprd??"","Total Nurse HPRD":p.reported_total_nurse_hprd??"","State Median Nurse HPRD":y.avg_total_nurse_hprd??"","Turnover %":p.total_nursing_staff_turnover??"","State Median Turnover %":y.avg_turnover??"","Case Mix":p.nursing_casemix_index_ratio??"","State Median Case Mix":y.avg_casemix??"","SS Rehosp %":L.ss_rehosp??"","State SS Rehosp %":L.state_ss_rehosp??"","LS Hosp /1k Days":L.ls_hosp??"","State LS Hosp /1k Days":L.state_ls_hosp??"",Penalties:p.total_number_of_penalties??""}});Gt(m,["Date","Overall","Health","Staffing","QM","Beds","ADC","Occupancy %","State Median Occ %","RN HPRD","State Median RN HPRD","Total Nurse HPRD","State Median Nurse HPRD","Turnover %","State Median Turnover %","Case Mix","State Median Case Mix","SS Rehosp %","State SS Rehosp %","LS Hosp /1k Days","State LS Hosp /1k Days","Penalties"],`trends_${n}.csv`)},className:"flex items-center gap-1 text-xs text-sky-600 hover:text-sky-800 font-medium",children:[e.jsx(Ue,{size:13})," Export CSV"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm min-w-[640px]",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsx("tr",{children:["Date","Stars","Occ %","RN HPRD","Total HPRD","Turnover %","Case Mix","SS Rehosp %","LS Hosp/1k"].map(m=>e.jsx(Ei,{children:m},m))})}),e.jsx("tbody",{className:"divide-y divide-slate-100",children:d.map((m,p)=>{const i=Ne(m.number_of_certified_beds),h=Ne(m.average_number_of_residents_per_day),v=i>0&&h>0?(h/i*100).toFixed(1)+"%":"â",y=a[m.snapshot_date?.slice(0,7)]||{};return e.jsxs("tr",{className:"hover:bg-slate-50",children:[e.jsx(ne,{mono:!0,children:m.snapshot_date?.slice(0,7)}),e.jsx(ne,{children:e.jsx($t,{rating:m.overall_rating})}),e.jsx(ne,{children:v}),e.jsx(ne,{children:m.reported_rn_hprd??"â"}),e.jsx(ne,{children:m.reported_total_nurse_hprd??"â"}),e.jsx(ne,{children:m.total_nursing_staff_turnover?m.total_nursing_staff_turnover+"%":"â"}),e.jsx(ne,{children:m.nursing_casemix_index_ratio??"â"}),e.jsx(ne,{children:y.ss_rehosp!=null?y.ss_rehosp.toFixed(1)+"%":"â"}),e.jsx(ne,{children:y.ls_hosp!=null?y.ls_hosp.toFixed(2):"â"})]},p)})})]})}),c&&!r&&e.jsxs("button",{onClick:()=>l(!0),className:"w-full py-2.5 text-xs font-medium text-sky-600 hover:text-sky-700 hover:bg-sky-50 border-t border-slate-100 transition-colors",children:["Load all ",o.length," rows"]})]})}const Fa=[{key:"quality",label:"Clinical Quality",short:"Quality",weight:.3},{key:"staffing",label:"Staffing & Leadership",short:"Staffing",weight:.22},{key:"momentum",label:"Trend & Momentum",short:"Momentum",weight:.18},{key:"peer",label:"State Peer Rank",short:"Peer rank",weight:.15},{key:"financial",label:"Financial Health",short:"Financial",weight:.15}];function bo(t,s){if(!t||!s)return null;const a=Fa.map(o=>{const d=t[o.key],c=s[o.key];if(d==null||c==null)return{...o,diff:null,pts:0};const m=d-c;return{...o,diff:m,pts:m*o.weight}}),n=(t.acuity_bonus??0)-(s.acuity_bonus??0),r=(t.sff_penalty??0)-(s.sff_penalty??0),l=a.reduce((o,d)=>o+d.pts,0)+n+r;return{rows:a,acuity:n,sff:r,net:l}}const Ls=t=>t==null?null:t<365?`${Math.round(t)} days`:`${(t/365).toFixed(1)} yrs`,Os=t=>
6`$${Math.round(t).toLocaleString()}`;function Es(t){return t<180?20:t<540?55:t<1095?80:100}function _o(t){return t<=.1?100:t<=2?85:t<=5?70:t<=10?50:t<=20?30:10}function jo(t){return t===0?100:t<=1?75:t<=2?50:t<=3?30:10}function vo(t){return t===0?100:t<1e4?85:t<5e4?65:t<1e5?40:15}const No={quality:"quality",staffing:"staffing",occupancy:"momentum",financial:"financial"},wo={quality:"quality measures, deficiency count and severe tags",staffing:"total and RN HPRD, and turnover level",occupancy:"census direction, turnover direction and occupancy",financial:"operating margin and revenue per day"};function ko(t,s){const a={quality:{helps:[],costs:[],context:[]},staffing:{helps:[],costs:[],context:[]},occupancy:{helps:[],costs:[],context:[]},regulatory:{helps:[],costs:[],context:[]},financial:{helps:[],costs:[],context:[]}};if(!t)return a;const n=(l,o,d)=>{o>=75?a[l].helps.push(`${d} â scores ${o}`):o<=55&&a[l].costs.push(`${d} â scores ${o}`)};if(t.total_fines!=null){const l=vo(Number(t.total_fines));n("quality",l,Number(t.total_fines)===0?"No CMS fines on file":`${Os(t.total_fines)} in CMS fines`)}if(t.nursing_agency_pct!=null){const l=Number(t.nursing_agency_pct);n("staffing",_o(l),`Agency at ${l.toFixed(1)}% of nursing hours`)}if(t.admin_tenure_days!=null?n("staffing",Es(Number(t.admin_tenure_days)),`Administrator ${Ls(t.admin_tenure_days)} in seat`):a.staffing.costs.push("No administrator tenure reported in PBJ â scored 25, not skipped"),t.don_tenure_days!=null?n("staffing",Es(Number(t.don_tenure_days)),`DON ${Ls(t.don_tenure_days)} in seat`):a.staffing.costs.push("No DON tenure reported in PBJ â scored 25, not skipped"),t.admin_turnover!=null){const l=Number(t.admin_turnover);n("staffing",jo(l),l===0?"No administrator departures on record":`${l} administrator departure${l===1?"":"s"} on record`)}if(s?.peer!=null){const l=Math.round(s.peer),d=`${t.overall_rating?`${t.overall_rating}-star`:"Star"} rating sits at the ${l}th percentile in your state`;l>=70?a.regulatory.helps.push(d):l<=50?a.regulatory.costs.push(d):a.regulatory.context.push(d)}let r=!1;t.operating_margin_pct==null&&t.net_revenue_ppd==null?(r=!0,a.financial.costs.push("No cost report on file â this domain is scored a flat 25 out of 100 on missing data, not on performance")):(t.operating_margin_pct!=null&&a.financial.context.push(`Operating margin ${Number(t.operating_margin_pct).toFixed(1)}%`),t.net_revenue_ppd!=null&&a.financial.context.push(`net revenue ${Os(t.net_revenue_ppd)}/day`)),t.occupancy_pct!=null&&a.occupancy.context.push(`Occupancy ${Number(t.occupancy_pct).toFixed(1)}%`);for(const[l,o]of Object.entries(No)){const d=s?.[o];if(d==null||l==="financial"&&r)continue;const c=Math.round(d),m=wo[l];c>=70?a[l].helps.push(`Domain scores ${c} of 100 against your state`):c<=50&&a[l].costs.push(m?`Domain scores ${c} of 100 against your state â the rest is ${m}, ranked in-state and not broken out here`:`Domain scores ${c} of 100 against your state`)}return a}const wt=[{key:"insight_rank",label:"Rank",on:!0,fixed:!0,type:"rank",tip:"Rank by SNF InsightScore among this nearby cohort (1 = highest InsightScore). Stays fixed regardless of how you sort the table."},{key:"insight_score",label:"InsightScore",on:!0,fixed:!1,type:"insight",tip:"SNF InsightScore â proprietary 0-100 composite blending clinical quality, staffing & leadership, momentum, market position, and financial health. Higher is better. Click the arrow on any score to see the full breakdown against your facility."},{key:"provider_name",label:"Facility",on:!0,fixed:!0,type:"facility"},{key:"citytown",label:"City",on:!0,fixed:!0,type:"text"},{key:"distance_miles",label:"Miles",on:!0,fixed:!0,type:"num1"},{key:"overall_rating",label:"Overall",on:!0,type:"stars",tip:"CMS Five-Star composite rating."},{key:"health_inspection_rating",label:"Health",on:!0,type:"stars",tip:"Health inspection rating."},{key:"staffing_rating",label:"Staffing",on:!1,type:"stars",tip:"Staffing rating based on HPRD."},{key:"qm_rating",label:"Quality",on:!0,type:"stars",tip:"Quality measure rating."},{key:"special_focus_status",label:"SFF",on:!1,type:"sff",tip:'Special Focus Facility flag. CMS designates the worst-performing facilities as SFF; "Candidate" means at risk. Anything here is a major market signal.'},{key:"number_of_certified_beds",label:"Beds",on:!0,type:"int"},{key:"average_number_of_residents_per_day",label:"ADC",on:!0,type:"num1",tip:"Average Daily Census."},{key:"adc_yoy_change",label:"ADC YoY",on:!0,type:"num1_signed",tip:"Year-over-year change in Average Daily Census, in absolute residents (current ADC minus ADC from ~12 months prior). Positive = census growing, negative = shrinking."},{key:"occupancy_pct",label:"Occ %",on:!0,type:"pct1",tip:"ADC / Certified Beds."},{key:"case_mix_index",label:"Case Mix",on:!0,type:"num2",tip:"Nursing case mix index ratio â higher indicates more complex patient needs."},{key:"total_nurse_hprd",label:"Nurse HPRD",on:!1,type:"num2",tip:"Total nursing hours per resident day."},{key:"rn_hprd",label:"RN HPRD",on:!1,type:"num2",tip:"Registered Nurse hours per resident day."},{key:"lpn_hprd",label:"LPN HPRD",on:!1,type:"num2",tip:"Licensed Practical Nurse hours per resident day."},{key:"cna_hprd",label:"CNA HPRD",on:!1,type:"num2",tip:"Certified Nurse Aide hours per resident day."},{key:"nursing_turnover",label:"Nurs. Turnover",on:!1,type:"pct1",tip:"Annual nursing staff turnover."},{key:"nursing_agency_pct",label:"Agency %",on:!1,type:"pct1",tip:"% of nursing hours (RN+LPN+CNA) provided by agency/contract staff in the latest PBJ quarter. Leading indicator of turnover and cost pressure."},{key:"admin_tenure_days",label:"Admin Tenure",on:!1,type:"days",tip:"Current administrator tenure in days, from PBJ payroll data. Short tenures signal instability."},{key:"don_tenure_days",label:"DON Tenure",on:!1,type:"days",tip:"Current Director of Nursing tenure in days, from PBJ payroll data."},{key:"admin_turnover",label:"Admin Turn.",on:!1,type:"int",tip:"Number of administrators who have left the facility."},{key:"health_deficiency_count",label:"Deficiencies",on:!1,type:"int",tip:"Total health deficiencies cited in the most recent standard survey cycle."},{key:"total_fines",label:"Fines $",on:!1,type:"dollar",tip:"Total amount of CMS fines levied against this facility (cumulative)."},{key:"number_of_fines",label:"# Fines",on:!1,type:"int",tip:"Number of CMS fines levied against this facility (cumulative)."}
6,{key:"ss_rehospitalization",label:"SS Rehosp",on:!1,type:"pct1",tip:"% of short-stay residents rehospitalized after NH admission. Lower is better."},{key:"ss_ed_visits",label:"SS ED %",on:!1,type:"pct1",tip:"% of short-stay residents with outpatient ED visit. Lower is better."},{key:"ls_hospitalizations",label:"LS Hosp",on:!1,type:"num1",tip:"Hospitalizations per 1,000 long-stay resident days. Lower is better."},{key:"ls_ed_visits",label:"LS ED",on:!1,type:"num1",tip:"Outpatient ED visits per 1,000 long-stay resident days. Lower is better."},{key:"ma_penetration_pct",label:"MA Pen %",on:!1,type:"pct1",tip:"Medicare Advantage enrollment % in the facility's county. Higher MA penetration means more referrals run through plan networks."},{key:"operating_margin_pct",label:"Op Margin",on:!1,type:"pct1",tip:"Operating margin from cost report. Revenue minus costs / revenue."},{key:"net_revenue_ppd",label:"Rev PPD",on:!1,type:"dollar",tip:"Net revenue per patient day (after Medicare PPS adjustment)."},{key:"cost_per_day",label:"Exp PPD",on:!1,type:"dollar",tip:"Total cost per patient day from cost report."},{key:"dso_days",label:"DSO",on:!1,type:"num0",tip:"Days sales outstanding. Net AR / (Revenue / 365)."},{key:"overhead_pct",label:"Overhead",on:!1,type:"pct1",tip:"Admin & General costs as % of revenue."},{key:"medicaid_day_pct",label:"Medicaid %",on:!1,type:"pct1",tip:"Medicaid patient days as % of total days from cost report."},{key:"chain_name",label:"Chain",on:!1,type:"text"},{key:"ownership_type",label:"Ownership",on:!1,type:"text_sm"}];function So({row:t,isMe:s,centerScore:a}){const n=t.insight_parts,r=t.insight_gap,l=(c,m=0)=>c==null?"â":Number(c).toFixed(m),o=(c,m=1)=>c==null?"â":`${c>0?"+":c<0?"â":""}${Math.abs(c).toFixed(m)}`,d=c=>c?"text-slate-700":"text-slate-400";return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-700 mb-2",children:s?"Your InsightScore, by domain":e.jsxs(e.Fragment,{children:["Why ",Ce(t.provider_name)," scores ",l(t.insight_score)," vs your ",l(a)]})}),e.jsxs("table",{className:"w-full text-[11px]",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-slate-400",children:[e.jsx("th",{scope:"col",className:"text-left font-medium pb-1",children:"Domain"}),e.jsx("th",{scope:"col",className:"text-right font-medium pb-1 w-16",children:"Weight"}),e.jsx("th",{scope:"col",className:"text-right font-medium pb-1 w-16",children:s?"Score":"Them"}),!s&&e.jsx("th",{scope:"col",className:"text-right font-medium pb-1 w-16",children:"You"}),!s&&e.jsx("th",{scope:"col",className:"text-right font-medium pb-1 w-20",children:"Points"})]})}),e.jsxs("tbody",{children:[Fa.map((c,m)=>{const p=r?.rows?.[m];return e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"py-1 text-slate-600",children:c.label}),e.jsxs("td",{className:"py-1 text-right text-slate-400 tabular-nums",children:[(c.weight*100).toFixed(0),"%"]}),e.jsx("td",{className:"py-1 text-right text-slate-700 tabular-nums",children:l(n[c.key])}),!s&&e.jsx("td",{className:"py-1 text-right text-slate-500 tabular-nums",children:l(p?.diff!=null?n[c.key]-p.diff:null)}),!s&&e.jsx("td",{className:`py-1 text-right tabular-nums font-medium ${d(p?.pts)}`,children:p?.diff==null?"â":o(p.pts)})]},c.key)}),e.jsxs("tr",{className:"border-t border-slate-200",children:[e.jsxs("td",{className:"py-1 text-slate-600",children:["Acuity adjustment",e.jsxs("span",{className:"text-slate-400",children:[" â case mix ",t.case_mix_index!=null?Number(t.case_mix_index).toFixed(2):"â"]})]}),e.jsx("td",{className:"py-1 text-right text-slate-400",children:"â"}),e.jsx("td",{className:"py-1 text-right text-slate-700 tabular-nums",children:o(n.acuity_bonus,1)}),!s&&e.jsx("td",{className:"py-1 text-right text-slate-500 tabular-nums",children:o((n.acuity_bonus??0)-(r?.acuity??0),1)}),!s&&e.jsx("td",{className:`py-1 text-right tabular-nums font-medium ${d(r?.acuity)}`,children:o(r?.acuity,1)})]}),(n.sff_penalty!==0||r?.sff!==0)&&e.jsxs("tr",{className:"border-t border-slate-100",children:[e.jsx("td",{className:"py-1 text-slate-600",children:"Special Focus penalty"}),e.jsx("td",{className:"py-1 text-right text-slate-400",children:"â"}),e.jsx("td",{className:"py-1 text-right text-slate-700 tabular-nums",children:o(n.sff_penalty,0)}),!s&&e.jsx("td",{className:"py-1 text-right text-slate-500 tabular-nums",children:o((n.sff_penalty??0)-(r?.sff??0),0)}),!s&&e.jsx("td",{className:`py-1 text-right tabular-nums font-medium ${d(r?.sff)}`,children:o(r?.sff,0)})]}),!s&&r&&e.jsxs("tr",{className:"border-t-2 border-slate-300 font-semibold",children:[e.jsx("td",{className:"py-1 text-slate-700",colSpan:4,children:"Net score difference"}),e.jsx("td",{className:"py-1 text-right tabular-nums text-slate-800",children:o(r.net)})]})]})]}),e.jsxs("p",{className:"text-[10px] text-slate-400 mt-2 leading-relaxed",children:["Points = domain difference x weight, which is what actually moves rank: a 22-point gap on a 15% domain moves the score less than a 20-point gap on a 30% domain. The acuity adjustment and Special Focus penalty are applied after the weighted domains.",n.snapshot_date&&e.jsxs(e.Fragment,{children:[" InsightScore snapshot ",n.snapshot_date,"; CMS columns in the table may be more recent."]})]})]})}function Co({ccn:t,facility:s,navigate:a}
6){const n={radius_miles:15,min_competitors:10,limit:50},{data:r,isLoading:l}=ee({queryKey:["competitors",t,n],queryFn:()=>Gs(t,n)}),[o,d]=b.useState("insight_score"),[c,m]=b.useState("desc"),[p,i]=b.useState(()=>wt.filter(x=>x.on).map(x=>x.key)),[h,v]=b.useState(!1),[y,L]=b.useState(!1),[D,j]=b.useState(null),M=b.useMemo(()=>{const x=r?.results??[];if(x.some(V=>V.is_center||V.ccn===t)||!s)return x;const $=s,T=parseFloat($.number_of_certified_beds)||0,F=parseFloat($.average_number_of_residents_per_day)||0;return[{ccn:t,provider_name:$.provider_name,provider_address:$.provider_address,citytown:$.citytown,state:$.state,zip_code:$.zip_code,ownership_type:$.ownership_type,chain_name:$.chain_name,overall_rating:$.overall_rating,health_inspection_rating:$.health_inspection_rating,staffing_rating:$.staffing_rating,qm_rating:$.qm_rating,number_of_certified_beds:$.number_of_certified_beds,average_number_of_residents_per_day:$.average_number_of_residents_per_day,occupancy_pct:T>0&&F>0?Math.round(F/T*1e3)/10:null,total_nurse_hprd:$.reported_total_nurse_hprd?parseFloat($.reported_total_nurse_hprd):null,rn_hprd:$.reported_rn_hprd?parseFloat($.reported_rn_hprd):null,nursing_turnover:$.total_nursing_staff_turnover?parseFloat($.total_nursing_staff_turnover):null,case_mix_index:$.nursing_casemix_index_ratio?parseFloat($.nursing_casemix_index_ratio):null,admin_turnover:$.administrator_turnover?parseInt($.administrator_turnover):null,ss_rehospitalization:$.qm_short_stay_rehospitalization,ss_ed_visits:$.qm_short_stay_ed_visits,ls_hospitalizations:$.qm_long_stay_hospitalizations,ls_ed_visits:$.qm_long_stay_ed_visits,is_center:!0,distance_miles:0,latitude:$.latitude,longitude:$.longitude},...x]},[r,s,t]),f=b.useMemo(()=>{if(!M.length)return[];const x=M.map((T,F)=>({i:F,s:T.insight_score??-1})).sort((T,F)=>F.s-T.s),P=M.map(T=>({...T}));x.forEach((T,F)=>{P[T.i].insight_rank=T.s>=0?F+1:null});const $=P.find(T=>T.is_center||T.ccn===t)?.insight_parts;return P.forEach(T=>{const F=T.is_center||T.ccn===t;T.insight_gap=F?null:bo(T.insight_parts,$)}),P},[M,t]),w=f.find(x=>x.is_center||x.ccn===t),B=w?.insight_rank,z=f.length,_=b.useMemo(()=>wt.filter(x=>p.includes(x.key)),[p]),S=x=>{o===x?m(P=>P==="asc"?"desc":"asc"):(d(x),m(x==="insight_score"?"desc":"asc"))},C=b.useMemo(()=>{const x=[...f],P=wt.find($=>$.key===o);return x.sort(($,T)=>{let F=$[o],R=T[o];return F==null?1:R==null?-1:P?.type==="text"||P?.type==="text_sm"||P?.type==="facility"||P?.type==="sff"?(F=String(F).toLowerCase(),R=String(R).toLowerCase(),c==="asc"?F.localeCompare(R):R.localeCompare(F)):(F=parseFloat(F)||0,R=parseFloat(R)||0,c==="asc"?F-R:R-F)}),x},[f,o,c]),u=(x,P)=>{if(P.type==="insight"){const F=x.insight_score;if(F==null)return"â";const R=F>=70?"bg-emerald-500":F>=50?"bg-sky-500":F>=35?"bg-amber-500":"bg-red-500",V=D===x.ccn;return e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded font-semibold text-xs text-white ${R}`,children:[F.toFixed(0),e.jsx("span",{className:"w-8 h-1.5 rounded-full overflow-hidden",style:{backgroundColor:"rgba(255,255,255,0.3)"},children:e.jsx("span",{className:"block h-full rounded-full bg-white",style:{width:`${F}%`}})})]}),x.insight_parts&&e.jsx("button",{onClick:X=>{X.stopPropagation(),j(V?null:x.ccn)},"aria-expanded":V,"aria-label":`${V?"Hide":"Show"} InsightScore breakdown for ${Ce(x.provider_name||"")}`,className:"text-slate-400 hover:text-sky-600 transition-colors",children:V?e.jsx(Ae,{size:13}):e.jsx(ye,{size:13})})]})}if(P.type==="sff"){const F=x.special_focus_status;if(!F)return e.jsx("span",{className:"text-slate-300",children:"â"});const R=/sff|special focus/i.test(F)&&!/candidate/i.test(F),V=/candidate/i.test(F),X=R?"bg-red-500 text-white":V?"bg-amber-500 text-white":"bg-slate-200 text-slate-700",O=R?"SFF":V?"Candidate":F;return e.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-semibold ${X}`,children:O})}const $=x[P.key];if($==null||$==="")return"â";const T=(F,R)=>{if(R==null||isNaN(R))return null;const V=Number(R),X=(O,G)=>V>O?"text-rose-700 font-medium":V>G?"text-amber-700":null;switch(F){case"nursing_turnover":return X(75,50);case"nursing_agency_pct":return X(20,10);case"admin_turnover":return X(2,1);case"total_fines":return X(2e5,5e4);case"dso_days":return X(90,60);case"overhead_pct":return X(20,15);
6case"ss_rehospitalization":return X(25,20);case"ss_ed_visits":return X(18,12);case"ls_hospitalizations":return X(2.5,1.5);case"ls_ed_visits":return X(1.5,1);default:return null}};switch(P.type){case"rank":return e.jsxs("span",{className:"font-semibold text-slate-700 tabular-nums",children:["#",Math.round(parseFloat($))]});case"stars":return e.jsx($t,{rating:$});case"num1":{const F=T(P.key,$),R=parseFloat($).toFixed(1);return F?e.jsx("span",{className:F,children:R}):R}case"num0":{const F=T(P.key,$),R=Math.round(parseFloat($)).toLocaleString();return F?e.jsx("span",{className:F,children:R}):R}case"num2":{const F=T(P.key,$),R=parseFloat($).toFixed(2);return F?e.jsx("span",{className:F,children:R}):R}case"pct1":{const F=T(P.key,$),R=parseFloat($).toFixed(1)+"%";return F?e.jsx("span",{className:F,children:R}):R}case"pct1_signed":{const F=parseFloat($),R=F>0?"text-emerald-700 font-medium":F<0?"text-rose-700 font-medium":"text-slate-500",V=F>0?"+":"";return e.jsxs("span",{className:R,children:[V,F.toFixed(1),"%"]})}case"num1_signed":{const F=parseFloat($),R=F>0?"text-emerald-700 font-medium":F<0?"text-rose-700 font-medium":"text-slate-500",V=F>0?"+":"";return e.jsxs("span",{className:R,children:[V,F.toFixed(1)]})}case"dollar":{const F=T(P.key,$),R="$"+Math.round(parseFloat($)).toLocaleString();return F?e.jsx("span",{className:F,children:R}):R}case"int":return Number($).toLocaleString();case"days":{const F=Math.round(parseFloat($));return F>=365?(F/365).toFixed(1)+" yrs":F.toLocaleString()+" d"}case"text":return Ce($);case"text_sm":return Ce($);default:return $}};if(l)return e.jsx(Te,{});const g=z>0?z-1:0,A=r?.expanded?`${g} nearest competitors (expanded beyond ${r.radius_miles} mi to ${r.effective_radius} mi)`:`${g} competitors within ${r?.radius_miles} miles`;return e.jsxs("div",{className:"space-y-2",children:[B!=null&&e.jsxs("div",{className:`rounded-lg px-4 py-2.5 flex items-center gap-3 border ${B<=3?"bg-emerald-50 border-emerald-200":B<=5?"bg-sky-50 border-sky-200":"bg-slate-50 border-slate-200"}`,children:[e.jsxs("span",{className:`text-2xl font-bold ${B<=3?"text-emerald-700":B<=5?"text-sky-700":"text-slate-600"}`,children:["#",B]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-sm font-semibold text-slate-700",children:[w?.provider_name," ranks ",e.jsxs("span",{className:"font-bold",children:["#",B]})," out of ",z," facilities by InsightScore"]}),e.jsxs("p",{className:"text-xs text-slate-500",children:["InsightScore: ",w?.insight_score!=null?Math.round(w.insight_score):"â"," / 100"]})]})]}),e.jsx(Ut,{children:"Based on straight-line distance, not drive time or travel distance."}),(()=>{const x=s?.insight_score,P=[{key:"quality",label:"Clinical Quality",weight:30,mix:"Quality measures 40% · deficiency count 25% · severe tags 15% · fines 10% · VBP 10%",helps:"Zero severe (G+) tags scores 100 here; 1-2 scores 70. No fines scores 100. Deficiency count is graded against 2.5x your state median, so coming in under the median scores well.",hurts:"6+ severe tags drops that piece to 10. Fines of $100K+ drop the fines piece to 15; even $10-50K costs you. More deficiencies than 2.5x the state median scores 0."},{key:"staffing",label:"Staffing & Leadership",weight:22,mix:"Total HPRD 25% · RN HPRD 20% · agency 15% · turnover 15% · admin+DON tenure 15% · admin churn 10%",helps:"Agency under 2% of nursing hours scores 85, under 0.1% scores 100. An administrator or DON past 3 years scores 100; past 18 months, 80. Never having lost an administrator scores 100.",hurts:"Agency over 20% of hours drops that piece to 10. A leader under 6 months in seat scores 20 â a new administrator visibly costs you here. Four or more administrator departures scores 10."},{key:"occupancy",label:"Trend & Momentum",weight:18,mix:"Census direction 35% · turnover direction 35% · occupancy level 30%",helps:"Direction beats level: census rising over the last six snapshots scores 85 regardless of where it started, and so does turnover falling. High occupancy against your state adds the rest.",hurts:"Census or turnover moving the wrong way scores 20 â the single steepest per-point drop in the score. Flat scores 55, so standing still costs you against a market that is improving."},{key:"regulatory",label:"State Peer Rank",weight:15,mix:"CMS overall star rating, ranked within your state",helps:"This is the only place stars count. Because it is a state rank, the same 4 stars is worth more in a strong-rated state than a weak one.",hurts:"Nothing else here â a low star rating cannot cost you more than 15 points of the composite."},{key:"financial",label:"Financial Health",weight:15,mix:"Operating margin 60% · net revenue per patient day 40%",helps:"Both are ranked against other facilities in your state from the latest filed cost report.",hurts:"No cost report on file is scored 25 out of 100, not skipped. A facility that has not filed is carrying a below-average financial score it did not earn."}],$=F=>F==null?"bg-slate-200":F>=70?"bg-emerald-500":F>=50?"bg-sky-500":F>=35?"bg-amber-500":"bg-red-500",T=ko(w,w?.insight_parts);return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("button",{onClick:()=>L(F=>!F),className:"w-full px-4 py-2.5 flex items-center justify-between text-left hover:bg-slate-50 transition-colors",children:[e.jsxs("span",{className:"text-sm font-semibold text-slate-700 flex items-center gap-2",children:[e.jsx(Ye,{size:14,className:"text-sky-500"}),"How is InsightScore calculated?"]}),y?e.jsx(Ae,{size:16,className:"text-slate-400"}):e.jsx(ye,{size:16,className:"text-slate-400"})]}),y&&e.jsxs("div",{className:"px-4 pb-4 pt-1 border-t border-slate-100 space-y-4",children:[e.jsxs("p",{className:"text-xs text-slate-600 leading-relaxed",children:["SNF InsightScore is a 0-100 composite built to answer one question: ",e.jsx("span",{className:"font-semibold",children:"how is this facility actually performing right now?"})," Five weighted domains, each built from underlying operational data and ranked against other facilities in your state, then two adjustments. Everything that moves it is listed below."]}),e.jsx("div",{className:"space-y-2",children:P.map(F=>{const R=x?.[F.key],V=R!=null;return e.jsxs("div",{className:"flex items-start gap-3 py-1.5 border-b border-slate-50 last:border-b-0",children:[e.jsxs("div",{className:"w-44 flex-shrink-0",children:[e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-700",children:F.label}),e.jsxs("span",{className:"text-[10px] font-medium text-slate-400",children:[F.weight,"%"]})]}),V&&e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx("div",{className:"flex-1 h-1.5 bg-slate-100 rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${$(R)}`,style:{width:`${Math.min(100,Math.max(0,R))}%`}})}),e.jsx("span",{className:"text-[10px] font-semibold text-slate-500 tabular-nums w-7 text-right",children:Math.round(R)})]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[11px] text-slate-500 leading-snug",children:F.mix}),e.jsxs("div",{className:"mt-1 pl-3 border-l border-slate-200 space-y-0.5",children:[e.jsxs("p",{className:"text-[11px] text-slate-500 leading-snug",children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Helps: "}),T[F.key].helps.length?T[F.key].helps.join(" · "):e.jsxs("span",{className:"text-slate-400",children:["In general â ",F.helps]})]}),e.jsxs("p",{className:"text-[11px] text-slate-500 leading-snug",children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Costs you: "}),T[F.key].costs.length?T[F.key].costs.join(" · "):e.jsxs("span",{className:"text-slate-400",children:[R!=null&&R>=60?"Nothing here is scoring low for you. ":"","In general â ",F.hurts]})]}),T[F.key].context.length>0&&e.jsxs("p",{className:"text-[11px] text-slate-400 leading-snug",children:[e.jsx("span",{className:"font-semibold",children:"Your values: "}),T[F.key].context.join(" · ")," â ranked against your state"]})]})]})]},F.key)})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1.5",children:"What the colors mean"}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-[11px] text-slate-600",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-emerald-500"})," 70+ Strong"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-sky-500"})," 50-69 Solid"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-amber-500"})," 35-49 Watch"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-sm bg-red-500"})," Under 35 At-risk"]})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-slate-400 uppercase tracking-wide mb-1.5",children:"Applied after the five domains"}),e.jsxs("div",{className:"text-[11px] text-slate-500 space-y-1 leading-relaxed pl-3 border-l border-slate-200",children:[e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Acuity bonus"})," â case mix 1.05+ adds 2 points, 1.10+ adds 3.5, 1.15+ adds 5.",w?.case_mix_index!=null&&e.jsxs("span",{className:"text-slate-600",children:[" ","Yours is ",Number(w.case_mix_index).toFixed(2),",",(w.insight_parts?.acuity_bonus??0)>0?` adding ${w.insight_parts.acuity_bonus} points.`:" which earns no bonus â 1.05 is the first step."]})," ","Between two close facilities this is often the whole difference in rank."]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Special Focus penalty"})," â a flat 12 points off, and ",e.jsx("span",{className:"font-semibold text-slate-600",children:"candidates take the same 12"})," as facilities already in the program.",w&&e.jsxs("span",{className:"text-slate-600",children:[" ",(w.insight_parts?.sff_penalty??0)!==0?`You are flagged ${w.special_focus_status} â this is costing you 12 points.`:"You are not flagged, so no penalty applies."]})]})]})]}),e.jsxs("div",{className:"text-[11px] text-slate-500 space-y-1.5 leading-relaxed",children:[e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Everything is scored against your own state."}),' Each metric is ranked against other SNFs in the same state, not nationally â so a score of 70 means "better than 70% of facilities in your state" on that measure. Moving the score means moving relative to your local market, not against a fixed target.']}),e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Missing data counts against you."})," When a metric has no value on file it is scored 25 out of 100, not skipped and not treated as average. An unfiled cost report or absent PBJ leadership data will hold the score down on its own. If a domain looks unexpectedly low, check whether the underlying data is actually reported before reading it as performance."]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"Why not just use star ratings?"})," Four of the five domains are built from underlying operational data rather than CMS stars. That avoids double-counting and lets the score move on momentum before the next star refresh. Stars enter only through State Peer Rank, capped at 15% of the composite."]}),e.jsxs("p",{children:[e.jsx("span",{className:"font-semibold text-slate-600",children:"What this does not include:"})," ownership, chain affiliation, payer mix, rates, or market share. It measures the facility's own operating performance, not the attractiveness of its business."]})]})]})]})})(),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 border-b border-slate-200 flex items-center justify-between",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700",children:A}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{onClick:()=>{const x=_.map($=>$.label),P=C.map($=>{const T={};for(const F of _){let R="";F.key==="insight_score"?R=$.insight_score!=null?Math.round($.insight_score):"":F.key==="provider_name"?R=$.provider_name?Ce($.provider_name):"":F.key==="distance_miles"?R=$.distance_miles!=null?Number($.distance_miles).toFixed(1):"":F.key==="special_focus_status"?R=$.special_focus_status||"":R=$[F.key]!=null?$[F.key]:"",T[F.label]=R}return T});Gt(P,x,`competitors_${t}.csv`)},className:"flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 border border-slate-200 rounded-lg px-2 py-1",children:[e.jsx(Ue,{size:12})," Export CSV"]}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>v(!h),className:"flex items-center gap-1 text-xs text-slate-500 hover:text-slate-700 border border-slate-200 rounded-lg px-2 py-1",children:[e.jsx(ua,{size:12})," Columns"]}),h&&e.jsx("div",{className:"absolute right-0 top-full mt-1 bg-white border border-slate-200 rounded-lg shadow-lg z-30 p-2 w-48 max-h-64 overflow-y-auto",children:wt.filter(x=>!x.fixed).map(x=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 text-xs text-slate-600 hover:bg-slate-50 rounded cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"accent-sky-500",checked:p.includes(x.key),onChange:P=>{i($=>P.target.checked?[...$,x.key]:$.filter(T=>T!==x.key))}}),x.label]},x.key))})]})]})]}),e.jsx("div",{className:"overflow-auto max-h-[650px]",children:e.jsxs("table",{className:"w-full min-w-max text-sm border-separate border-spacing-0",children:[e.jsx("thead",{className:"bg-slate-50",children:e.jsx("tr",{children:_.map((x,P)=>{const $=x.key==="insight_score",T=x.key==="provider_name",F=$?"left-0 z-30 shadow-[1px_0_0_#e2e8f0]":T?"left-[92px] z-30 shadow-[2px_0_0_#cbd5e1]":"z-20",R=$?{width:92,minWidth:92}:T?{width:220,minWidth:220}:void 0;return e.jsx("th",{scope:"col",onClick:()=>S(x.key),style:R,className:`sticky top-0 bg-slate-50 px-3 py-2 text-xs font-semibold text-slate-500 uppercase tracking-wide text-left cursor-pointer hover:text-slate-700 select-none whitespace-nowrap border-b border-slate-200 ${F}`,children:e.jsxs("span",{className:"inline-flex items-center gap-1",children:[x.label,x.tip&&e.jsx(le,{text:x.tip,size:10,position:"below",align:P===0?"left":"center"}),o===x.key&&(c==="asc"?e.jsx(ye,{size:11}):e.jsx(Ae,{size:11}))]})},x.key)})})}),e.jsx("tbody",{children:C.map(x=>{const P=x.is_center||x.ccn===t,$=P?"bg-slate-100":"bg-white";return e.jsxs(b.Fragment,{children:[e.jsx("tr",{onClick:()=>{Zs(C.map(T=>T.ccn)),window.open(`/facility/${x.ccn}`,"_blank")},className:`group cursor-pointer ${P?"border-l-4 border-l-sky-400":""}`,children:_.map(T=>{const F=T.key==="insight_score",R=T.key==="provider_name",V=F?`sticky left-0 z-10 ${$} group-hover:bg-sky-50 shadow-[1px_0_0_#e2e8f0]`:R?`sticky left-[92px] z-10 ${$} group-hover:bg-sky-50 shadow-[2px_0_0_#cbd5e1]`:`${$} group-hover:bg-sky-50`,X=F?{width:92,minWidth:92}:R?{width:220,minWidth:220}:void 0;return e.jsx("td",{style:X,className:`px-3 py-2 border-b border-slate-100 ${T.type==="text_sm"?"text-xs":""} ${P?"text-slate-500":"text-slate-600"} ${V}`,children:T.type==="facility"?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:`font-medium ${P?"text-slate-600":"text-slate-800"}`,children:[Ce(x.provider_name),P&&e.jsx("span",{className:"ml-1.5 text-[10px] font-semibold text-sky-500 uppercase",children:"You"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:x.ccn})]}):u(x,T)},T.key)})}),D===x.ccn&&x.insight_parts&&e.jsx("tr",{className:"bg-slate-50",children:e.jsx("td",{colSpan:_.length,className:"px-4 py-3 border-b border-slate-200",children:e.jsx(So,{row:x,isMe:P,centerScore:w?.insight_score})})})]},x.ccn)})})]})})]})]})}const Is={"0101":"All-Inclusive R&B","0110":"Room & Board (Private)","0120":"Room & Board (Semi-Private)","0130":"Room & Board (3+ Beds)","0191":"Level 1","0192":"Level 2","0193":"Level 3","0194":"Level 4",92523:"Speech-Language Pathology",97116:"Gait Training",97162:"PT Evaluation (Moderate)",97530:"Therapeutic Activities"};funct
6ion Mo({ccn:t,facility:s}){const[a,n]=b.useState(""),[r,l]=b.useState([]),[o,d]=b.useState("0120"),[c,m]=b.useState(null),[p,i]=b.useState(!1),[h,v]=b.useState(!1),L=[...h?[...Ds,...xo]:Ds,...r],D=ta({queries:L.map(g=>({queryKey:["facility-rate-analysis",t,g],queryFn:()=>wn(t,{billing_code:g}),enabled:!!t,staleTime:300*1e3}))}),M=Object.fromEntries(L.map((g,A)=>[g,D[A]]))[o],f=M?.data,w=b.useMemo(()=>f?.payers?.map(g=>g.payer)||[],[f]);b.useEffect(()=>{w.length&&c===null&&m(new Set(w))},[w,c]);const B=b.useMemo(()=>{const A=(f?.payers||[]).filter(P=>P.facility_rate==null||P.facility_rate<=mo),x=c?A.filter(P=>c.has(P.payer)):A;return In(x)},[f,c]),z=g=>{m(A=>{const x=new Set(A||w);return x.has(g)?x.size>1&&x.delete(g):x.add(g),x})},_=Number(s?.overall_rating)||null,S=_?_>=4?"Above Average":_>=3?"Average":"Below Average":null,C=_>=4?"text-emerald-600":_>=3?"text-amber-600":"text-red-500",u=_?_>=4?"CMS overall star rating of 4-5 stars places this facility above the national average. Ratings are based on health inspections, staffing levels, and quality measures.":_>=3?"CMS overall star rating of 3 stars indicates average performance. Ratings are based on health inspections, staffing levels, and quality measures.":"CMS overall star rating of 1-2 stars places this facility below the national average. Ratings are based on health inspections, staffing levels, and quality measures.":null;return e.jsxs("div",{className:"space-y-5",children:[e.jsx("div",{className:"bg-gradient-to-r from-slate-50 to-sky-50 rounded-xl border border-slate-200 p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700",children:"Clinical Quality vs. Rate Position"}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:"How this facility's quality compares to its negotiated rates in the market"})]}),e.jsxs("div",{className:"flex gap-3 md:gap-6 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wide",children:"Overall"}),e.jsxs("p",{className:"text-lg font-bold text-slate-700",children:[s?.overall_rating||"â",e.jsx("span",{className:"text-xs font-normal text-slate-400",children:"/5"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wide",children:"Health"}),e.jsxs("p",{className:"text-lg font-bold text-slate-700",children:[s?.health_inspection_rating||"â",e.jsx("span",{className:"text-xs font-normal text-slate-400",children:"/5"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wide",children:"Staffing"}),e.jsxs("p",{className:"text-lg font-bold text-slate-700",children:[s?.staffing_rating||"â",e.jsx("span",{className:"text-xs font-normal text-slate-400",children:"/5"})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wide",children:"Quality"}),e.jsxs("p",{className:"text-lg font-bold text-slate-700",children:[s?.qm_rating||"â",e.jsx("span",{className:"text-xs font-normal text-slate-400",children:"/5"})]})]}),S&&e.jsxs("div",{className:"cursor-help",title:u,children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wide",children:"Assessment"}),e.jsx("p",{className:`text-sm font-bold mt-1 ${C} underline decoration-dotted decoration-1 underline-offset-2`,children:S})]})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[L.map(g=>e.jsxs("button",{onClick:()=>d(g),className:`px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${o===g?"bg-sky-600 text-white border-sky-600":"border-slate-300 text-slate-600 hover:bg-slate-50"}`,children:[e.jsx("span",{className:"font-mono",children:g}),Is[g]&&e.jsx("span",{className:"ml-1.5 text-xs opacity-75",children:Is[g]})]},g)),e.jsx("span",{className:"text-slate-300 mx-1",children:"|"}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:h,onChange:g=>v(g.target.checked),className:"rounded border-slate-300 text-sky-600 focus:ring-sky-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Therapy Codes"})]}),e.jsx("span",{className:"text-slate-300 mx-1",children:"|"}),e.jsxs("div",{className:"relative",children:[e.jsxs("button",{onClick:()=>i(g=>!g),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-sm font-medium border transition-colors ${c&&c.size<w.length?"bg-sky-50 border-sky-300 text-sky-700":"border-slate-300 text-slate-600 hover:bg-slate-50"}`,children:["Payers ",c?`(${c.size}/${w.length})`:""]}),p&&e.jsxs("div",{className:"absolute z-20 top-full mt-1 left-0 bg-white border border-slate-200 rounded-xl shadow-lg p-3 min-w-[160px] max-w-[calc(100vw-2rem)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs font-semibold text-slate-500 uppercase",children:"Select Payers"}),e.jsx("button",{onClick:()=>i(!1),className:"text-slate-400 hover:text-slate-600 text-xs",children:"Done"})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsx("button",{onClick:()=>m(new Set(w)),className:"text-[10px] text-sky-600 hover:underline",children:"All"}),e.jsx("button",{onClick:()=>{const g=new Set(["uhc"]);!w.includes("uhc")&&w.length&&g.add(w[0]),m(g)},className:"text-[10px] text-sky-600 hover:underline",children:"UHC only"})]}),e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:w.map(g=>e.jsxs("label",{className:"flex items-center gap-2 px-2 py-1 rounded hover:bg-slate-50 cursor-pointer text-sm",children:[e.jsx("input",{type:"checkbox",checked:c?.has(g)||!1,onChange:()=>z(g),className:"rounded border-slate-300 text-sky-600 focus:ring-sky-500"}),e.jsx("span",{className:"text-slate-700",children:cs(g)})]},g))})]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const A=a.trim().toUpperCase();A&&!L.includes(A)&&(l(x=>[...x,A]),d(A),n(""))},className:"flex gap-1.5",children:[e.jsx("input",{value:a,onChange:g=>n(g.target.value),placeholder:"Add code...",className:"border border-slate-300 rounded-lg px-3 py-1.5 text-sm w-28 focus:outline-none focus:ring-2 focus:ring-sky-500"}),e.jsx("button",{type:"submit",className:"bg-slate-100 hover:bg-slate-200 text-slate-700 px-3 py-1.5 rounded-lg text-sm",children:"Add"})]})]}),e.jsx(zn,{pageContext:"facility_rates"}),M?.isLoading&&e.jsx(Te,{}),f&&e.jsx(e.Fragment,{children:B.length===0?e.jsxs("p",{className:"text-center text-slate-400 py-8 text-sm",children:["No rate data found for code ",o]}):e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-3",children:B.map((g,A)=>{g.county_rank&&g.county_total&&Math.round((1-(g.county_rank-1)/g.county_total)*100);const x=g.state_rank&&g.state_total?Math.round((1-(g.state_rank-1)/g.state_total)*100):null,P=g.facility_rate&&g.county_avg?((g.facility_rate-g.county_avg)/g.county_avg*100).toFixed(1):null,$=g.facility_rate&&g.state_avg?((g.facility_rate-g.state_avg)/g.state_avg*100).toFixed(1):null,T=x,F=_?Math.round(_/5*100):null;let R=null;return T!=null&&F!=null&&(F>=60&&T<40?R={text:"High quality, low rate",color:"text-red-500 bg-red-50",tip:"This facility has above-average quality (4-5 stars) but its negotiated rate ranks in the lower 40% of state peers. This may indicate an opportunity for rate renegotiation."}:F>=60&&T>=60?R={text:"High quality, high rate",color:"text-emerald-600 bg-emerald-50",tip:"This facility has above-average quality (4-5 stars) and its negotiated rate ranks in the upper 40% of state peers. Rate position aligns with quality."}:F<40&&T>=60&&(R={text:"Low quality, high rate",color:"text-amber-600 bg-amber-50",tip:"This facility has below-average quality (1-2 stars) but its negotiated rate ranks in the upper 40% of state peers. Rate may not be justified by clinical performance."})),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-3 bg-slate-50 border-b border-slate-100",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:g.displayLabel||cs(g.payer)}),R&&e.jsx("span",{className:`text-[10px] font-semibold px-2 py-0.5 rounded-full cursor-help ${R.color}`,title:R.tip,children:R.text})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[f?.npi&&g.facility_rate!=null?e.jsx(Bn,{payer:g.payer,billingCode:o,npi:f.npi,rate:g.facility_rate,children:e.jsxs("p",{className:"text-xl font-bold text-slate-800",children:["$",g.facility_rate.toLocaleStr
6ing(void 0,{minimumFractionDigits:0,maximumFractionDigits:0})]})}):e.jsxs("p",{className:"text-xl font-bold text-slate-800",children:["$",g.facility_rate?.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0})||"â"]}),f?.npi&&g.facility_rate!=null&&e.jsx(qn,{payer:g.payer,billingCode:o,npi:f.npi})]})]}),e.jsxs("div",{className:"grid grid-cols-2 divide-x divide-slate-100",children:[e.jsxs("div",{className:"px-4 py-3",children:[e.jsxs("p",{className:"text-xs text-slate-400 uppercase tracking-wide mb-2",children:["County (",f.county||"â",")"]}),e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-slate-700",children:["Rank #",g.county_rank||"â",e.jsxs("span",{className:"text-slate-400 font-normal",children:["/",g.county_total||"â"]})]}),P!=null&&e.jsxs("span",{className:`text-xs font-medium ${Number(P)>=0?"text-emerald-600":"text-red-500"}`,children:[Number(P)>=0?"+":"",P,"% vs avg"]})]}),g.county_min!=null&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:"flex justify-between text-[10px] text-slate-400 mb-0.5",children:[e.jsxs("span",{children:["$",g.county_min?.toFixed(0)]}),e.jsxs("span",{children:["avg $",g.county_avg?.toFixed(0)]}),e.jsxs("span",{children:["$",g.county_max?.toFixed(0)]})]}),e.jsx("div",{className:"h-2 bg-slate-100 rounded-full relative overflow-hidden",children:g.county_min!=null&&g.county_max!=null&&g.county_max>g.county_min&&e.jsx("div",{className:"absolute h-full bg-sky-500 rounded-full",style:{left:"0%",width:`${Math.min(100,(g.facility_rate-g.county_min)/(g.county_max-g.county_min)*100)}%`}})})]})]}),e.jsxs("div",{className:"px-4 py-3",children:[e.jsxs("p",{className:"text-xs text-slate-400 uppercase tracking-wide mb-2",children:["State (",f.state||"â",")"]}),e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("span",{className:"text-sm font-semibold text-slate-700",children:["Rank #",g.state_rank||"â",e.jsxs("span",{className:"text-slate-400 font-normal",children:["/",g.state_total||"â"]})]}),$!=null&&e.jsxs("span",{className:`text-xs font-medium ${Number($)>=0?"text-emerald-600":"text-red-500"}`,children:[Number($)>=0?"+":"",$,"% vs avg"]})]}),g.state_min!=null&&e.jsxs("div",{className:"mt-2",children:[e.jsxs("div",{className:"flex justify-between text-[10px] text-slate-400 mb-0.5",children:[e.jsxs("span",{children:["$",g.state_min?.toFixed(0)]}),e.jsxs("span",{children:["avg $",g.state_avg?.toFixed(0)]}),e.jsxs("span",{children:["$",g.state_max?.toFixed(0)]})]}),e.jsx("div",{className:"h-2 bg-slate-100 rounded-full relative overflow-hidden",children:g.state_min!=null&&g.state_max!=null&&g.state_max>g.state_min&&e.jsx("div",{className:"absolute h-full bg-sky-500 rounded-full",style:{left:"0%",width:`${Math.min(100,(g.facility_rate-g.state_min)/(g.state_max-g.state_min)*100)}%`}})})]})]})]})]},A)})})})}),e.jsxs("div",{className:"mt-8 pt-4 border-t border-slate-100 px-1 space-y-1",children:[e.jsxs("p",{className:"text-[11px] text-slate-500 italic leading-relaxed",children:[e.jsx("strong",{className:"not-italic font-medium text-slate-600",children:"Disclaimer."})," Rates are extracted from payer Transparency in Coverage files and have not been independently validated â errors, stale data, mis-classified billing classes, and duplicate contract entries are possible."]}),e.jsxs("p",{className:"text-[11px] text-slate-500 italic leading-relaxed",children:["Use the ",e.jsx(Hn,{size:10,className:"inline -mt-0.5"})," flag buttons on each rate to mark it as right, wrong, high, or low. Community feedback improves data quality for everyone."]})]})]})}function $o({ccn:t}){const{data:s}=ee({queryKey:["facility-salary-context",t],queryFn:()=>Fn(t),enabled:!!t});if(!s?.facility_salaries?.length)return null;const a=Object.fromEntries((s.state_benchmarks||[]).map(r=>[r.position_category,r])),n=r=>r!=null?`$${r.toFixed(2)}`:null;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsxs("h4",{className:"text-xs font-semibold text-slate-600 uppercase tracking-wide mb-3",children:["Salary vs. ",s.state||"State"," Average ",e.jsx("span",{className:"font-normal normal-case text-slate-400",children:"(hourly)"})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3",children:s.facility_salaries.map(r=>{const l=a[r.position_category],o=l&&r.median_min!=null&&l.median_min!=null&&r.median_min>=l.median_min;return e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3",children:[e.jsx("p",{className:"text-[10px] text-slate-500 uppercase font-medium truncate",children:r.position_category}),e.jsxs("p",{className:"text-sm font-bold text-slate-800 mt-0.5",children:[n(r.avg_min)," â ",n(r.avg_max)]}),l&&e.jsxs("p",{className:`text-[10px] mt-0.5 ${o?"text-emerald-600":"text-amber-600"}`,children:[o?"â":"â"," State avg: ",n(l.median_min)," â ",n(l.median_max)]}),e.jsxs("p",{className:"text-[10px] text-slate-400",children:[r.sample_size," posting",r.sample_size!==1?"s":""]})]},r.position_category)})})]})}function Fo({ccn:t,facility:s}){const{data:a,isLoading:n,isError:r}=ee({queryKey:["facility-jobs",t],queryFn:()=>An(t),enabled:!!t}),[l,o]=b.useState(null),d={AL:"Alabama",AK:"Alaska",AZ:"Arizona",AR:"Arkansas",CA:"California",CO:"Colorado",CT:"Connecticut",DE:"Delaware",DC:"District of Columbia",FL:"Florida",GA:"Georgia",HI:"Hawaii",ID:"Idaho",IL:"Illinois",IN:"Indiana",IA:"Iowa",KS:"Kansas",KY:"Kentucky",LA:"Louisiana",ME:"Maine",MD:"Maryland",MA:"Massachusetts",MI:"Michigan",MN:"Minnesota",MS:"Mississippi",MO:"Missouri",MT:"Montana",NE:"Nebraska",NV:"Nevada",NH:"New Hampshire",NJ:"New Jersey",NM:"New Mexico",NY:"New York",NC:"North Carolina",ND:"North Dakota",OH:"Ohio",OK:"Oklahoma",OR:"Oregon",PA:"Pennsylvania",RI:"Rhode Island",SC:"South Carolina",SD:"South Dakota",TN:"Tennessee",TX:"Texas",UT:"Utah",VT:"Vermont",VA:"Virginia",WA:"Washington",WV:"West Virginia",WI:"Wisconsin",WY:"Wyoming",PR:"Puerto Rico",GU:"Guam",VI:"Virgin Islands"},c=s?.state||"",m=d[c.toUpperCase()]||c,p=new URLSearchParams;m&&p.set("state",m);const i=`/jobs${p.toString()?"?"+p.toString():""}`,h=m;if(n)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(ge,{className:"animate-spin text-sky-500",size:24})});if(r||!a)return e.jsx("p",{className:"text-slate-400 text-center py-12",children:"Unable to load job postings."});const v=a.postings||[];if(!v.length)return e.jsxs("div",{className:"text-center py-16 text-slate-400",children:[e.jsx("p",{className:"text-lg font-medium",children:"No job postings matched to this facility."}),e.jsx("p",{className:"text-sm mt-1",children:"This facility may still have open positions that could not be matched by employer name or location."}),h?e.jsxs("a",{href:i,className:"text-sm text-sky-600 hover:text-sky-800 font-medium mt
6-2 inline-block",children:["Browse open jobs in ",h," â"]}):e.jsx("a",{href:"/jobs",className:"text-sm text-sky-600 hover:text-sky-800 font-medium mt-2 inline-block",children:"Browse all job postings â"})]});const y={exact:{label:"Exact",cls:"bg-emerald-100 text-emerald-700"},chain:{label:"Chain",cls:"bg-sky-100 text-sky-700"},geo:{label:"Geo",cls:"bg-amber-100 text-amber-700"},fuzzy:{label:"Fuzzy",cls:"bg-orange-100 text-orange-700"}},L=j=>j===0?"Today":j===1?"1d ago":`${j}d ago`,D=j=>j<=3?"text-emerald-600":j<=7?"text-sky-600":j<=14?"text-amber-600":"text-slate-400";return e.jsxs("div",{className:"space-y-4",children:[e.jsx($o,{ccn:t}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("p",{className:"text-sm text-slate-500",children:[v.length," active posting",v.length!==1?"s":""]}),h&&e.jsxs("a",{href:i,className:"text-xs text-sky-600 hover:text-sky-700 font-medium inline-flex items-center gap-1",children:["See all open jobs in ",h,e.jsx(da,{size:11})]})]}),e.jsx("div",{className:"space-y-3",children:v.map(j=>{const M=y[j.match_confidence]||{label:j.match_confidence,cls:"bg-slate-100 text-slate-600"},f=l===j.id;return e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm hover:border-slate-300 transition-colors",children:[e.jsx("div",{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-slate-800 text-sm",children:j.title}),e.jsxs("span",{className:`px-2 py-0.5 rounded-full text-[10px] font-medium ${M.cls}`,children:[M.label," ",j.match_score?`${Math.round(j.match_score)}%`:""]}),j.days_ago!=null&&e.jsx("span",{className:`text-[10px] font-medium ${D(j.days_ago)}`,children:L(j.days_ago)})]}),e.jsx("p",{className:"text-xs text-slate-500 mt-0.5",children:j.employer_name}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-slate-400 flex-wrap",children:[j.city&&e.jsxs("span",{children:[j.city,", ",j.state]}),j.job_type&&e.jsx("span",{className:"px-1.5 py-0.5 bg-slate-100 rounded text-slate-500",children:j.job_type}),j.source&&e.jsxs("span",{children:["via ",j.source]})]}),(j.salary_min||j.salary_max)&&e.jsxs("p",{className:"text-xs font-medium text-emerald-600 mt-1",children:[j.salary_min?`$${j.salary_min.toLocaleString()}`:"?"," - ",j.salary_max?`$${j.salary_max.toLocaleString()}`:"?",j.salary_type?` / ${j.salary_type}`:""]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[j.snippet&&e.jsx("button",{onClick:()=>o(f?null:j.id),className:"text-xs text-slate-400 hover:text-slate-600",children:f?e.jsx(Ae,{size:14}):e.jsx(ye,{size:14})}),j.apply_url&&e.jsx("a",{href:j.apply_url,target:"_blank",rel:"noopener noreferrer",className:"px-3 py-1.5 bg-sky-50 text-sky-600 text-xs font-medium rounded-lg hover:bg-sky-100 transition-colors",children:"View Listing"})]})]})}),f&&j.snippet&&e.jsx("div",{className:"px-4 pb-4 pt-0",children:e.jsx("p",{className:"text-xs text-slate-500 leading-relaxed bg-slate-50 rounded-lg p-3 whitespace-pre-line",children:j.snippet})})]},j.id)})}),e.jsx("div",{className:"mt-8 pt-4 border-t border-slate-100 px-1",children:e.jsxs("p",{className:"text-[11px] text-slate-500 italic leading-relaxed",children:[e.jsx("strong",{className:"not-italic font-medium text-slate-600",children:"Disclaimer."})," Job postings are matched by employer name and location â matches may not always be exact. Verify details on the original listing before taking action."]})})]})}const Ao=({children:t,...s})=>e.jsx(Nn,{compact:!0,...s,children:t});function Ne(t){const s=parseFloat(t);return isNaN(s)?null:s}function kt(t,s){return[...t].reverse().map(a=>({date:a.snapshot_date?.slice(0,7),...s(a)}))}const Po=t=>t!=null?t.toLocaleString():"â",zs=t=>t!=null?t.toFixed(1)+"%":"â",Ro=t=>t!=null?t.toFixed(1):"â",Do=t=>t!=null?t.toFixed(2):"â",To=t=>t!=null?t.toFixed(3):"â",Lo=t=>
6t!=null?"$"+Math.round(t).toLocaleString():"â",Aa=t=>t||"â",Oo=t=>t!=null?Math.round(t).toLocaleString()+" days":"â",Eo={int:Po,pct:zs,pct1:zs,float1:Ro,float2:Do,float3:To,dollar:Lo,str:Aa,days:Oo},Ie={star_ratings:{label:"Star Ratings",metrics:[{key:"overall_rating",label:"Overall Rating",fmt:"int",lowerBetter:!1},{key:"health_inspection_rating",label:"Health Inspection",fmt:"int",lowerBetter:!1},{key:"staffing_rating",label:"Staffing Rating",fmt:"int",lowerBetter:!1},{key:"qm_rating",label:"Quality Measure Rating",fmt:"int",lowerBetter:!1}]},operations:{label:"Operations",metrics:[{key:"number_of_certified_beds",label:"Certified Beds",fmt:"int",lowerBetter:!1},{key:"occupancy_pct",label:"Occupancy %",fmt:"pct",lowerBetter:!1},{key:"average_daily_census",label:"Avg Daily Census",fmt:"float1",lowerBetter:!1},{key:"casemix_index",label:"Case Mix Index",fmt:"float3",lowerBetter:!1},{key:"total_fines",label:"Total Fines",fmt:"dollar",lowerBetter:!0},{key:"total_penalties",label:"Total Penalties",fmt:"int",lowerBetter:!0},{key:"deficiency_score",label:"Deficiency Score",fmt:"float1",lowerBetter:!0},{key:"special_focus_status",label:"Special Focus",fmt:"str",lowerBetter:!1}]},staffing:{label:"Staffing",metrics:[{key:"total_nurse_hprd",label:"Total Nurse HPRD",fmt:"float2",lowerBetter:!1},{key:"rn_hprd",label:"RN HPRD",fmt:"float2",lowerBetter:!1},{key:"nurse_turnover",label:"Direct Care Turnover",fmt:"pct",lowerBetter:!0},{key:"rn_turnover",label:"RN Turnover %",fmt:"pct",lowerBetter:!0},{key:"admin_turnover",label:"Admin Turnover",fmt:"float1",lowerBetter:!0},{key:"don_tenure_days",label:"DON Tenure",fmt:"days",lowerBetter:!1},{key:"admin_tenure_days",label:"Admin Tenure",fmt:"days",lowerBetter:!1},{key:"nursing_admin_tenure_days",label:"Nursing Admin Tenure (Median)",fmt:"days",lowerBetter:!1},{key:"social_services_tenure_days",label:"Social Services Tenure (Median)",fmt:"days",lowerBetter:!1},{key:"agency_pct",label:"Agency %",fmt:"pct",lowerBetter:!0}]},financial:{label:"Financial",metrics:[{key:"revenue_per_day",label:"Revenue / Day",fmt:"dollar",lowerBetter:!1},{key:"cost_per_day",label:"Cost / Day",fmt:"dollar",lowerBetter:!0},{key:"operating_margin_pct",label:"Operating Margin %",fmt:"pct",lowerBetter:!1},{key:"true_net_income_margin_pct",label:"Net Income Margin %",fmt:"pct",lowerBetter:!1},{key:"medicare_day_pct",label:"Medicare Day %",fmt:"pct",lowerBetter:!1},{key:"medicaid_day_pct",label:"Medicaid Day %",fmt:"pct",lowerBetter:!1},{key:"labor_pct_of_costs",label:"Labor % of Costs",fmt:"pct",lowerBetter:!1},{key:"agency_pct_of_labor",label:"Agency % of Labor",fmt:"pct",lowerBetter:!0}]},quality_measures:{label:"Quality Measures",metrics:[{key:"ls_qm_points",label:"Long-Stay QM Points",fmt:"int",lowerBetter:!1},{key:"ss_qm_points_adjusted",label:"Short-Stay QM Points (Adj)",fmt:"int",lowerBetter:!1},{key:"overall_qm_points",label:"Overall QM Points",fmt:"int",lowerBetter:!1},{key:"qm_star_calculated",label:"QM Star (Calculated)",fmt:"int",lowerBetter:!1},{key:"measures_at_top_tier",label:"Measures at Top Tier",fmt:"int",lowerBetter:!1}]},clinical_acuity:{label:"Clinical Acuity",metrics:[{key:"nta_acuity_index",label:"NTA Acuity Index",fmt:"float1",lowerBetter:!1},{key:"nta_conditions_coded",label:"NTA Conditions Coded",fmt:"int",lowerBetter:!1}]},qrp_outcomes:{label:"QRP Outcomes",metrics:[{key:"ss_rehospitalization",label:"SS Rehospitalization %",fmt:"pct",lowerBetter:!0},{key:"ss_ed_visits",label:"SS ED Visits %",fmt:"pct",lowerBetter:!0},{key:"discharge_function",label:"Discharge Function %",fmt:"pct",lowerBetter:!1},{key:"return_to_community",label:"Return to Community %",fmt:"pct",lowerBetter:!1}]},medicare_advantage:{label:"Medicare Advantage",metrics:[{key:"ma_penetration_pct",label:"MA Penetration %",fmt:"pct",lowerBetter:!1},{key:"top_plan_share_pct",label:"Top Plan Share %",fmt:"pct",lowerBetter:!1}]}},Io=["star_ratings","operations","staffing"],ut=Io.flatMap(t=>(Ie[t]?.metrics||[]).map(s=>s.key)),zo=Object.values(Ie).flatMap(t=>t.metrics.map(s=>s.key)),Bs="snf_compare_metrics";function mc(){const t=Us(),[s,a]=Js(),[n,r]=b.useState(""),[l,o]=b.useState(""),[d,c]=b.useState(""),[m,p]=b.useState(!1),[i,h]=b.useState(()=>{try{const u=localStorage.getItem(Bs);if(u){const g=JSON.parse(u);if(Array.isArray(g)&&g.length>0)return g}}catch{}return ut}),v=u=>{localStorage.setItem(Bs,JSON.stringify(u))},y=u=>{const g=(Ie[u]?.metrics||[]).map(A=>A.key);h(A=>{const x=g.every(T=>A.includes(T));let P;x?P=A.filter(T=>!g.includes(T)):P=[...new Set([...A,...g])];const $=P.length>0?P:ut;return v($),$})},L=u=>{h(g=>{const A=g.includes(u)?g.filter(P=>P!==u):[...g,u],x=A.length>0?A:ut;return v(x),x})},D=b.useMemo(()=>Object.entries(Ie).filter(([,{metrics:u}])=>u.some(g=>i.includes(g.key))).map(([u])=>
6u),[i]),j=(s.get("ccns")||"").split(",").filter(Boolean),M=u=>{if(j.includes(u))return;const g=[...j,u];a({ccns:g.join(",")})},f=u=>{const g=j.filter(A=>A!==u);a(g.length?{ccns:g.join(",")}:{})},{data:w}=ee({queryKey:["facilities-search",d,l],queryFn:()=>Pn({q:d||void 0,state:l||void 0,page_size:20}),enabled:!!d}),B=D.join(","),{data:z,isLoading:_}=ee({queryKey:["facilities-compare",j.join(","),B],queryFn:()=>Rn(j.join(","),B),enabled:j.length>0&&D.length>0}),S=b.useMemo(()=>D.filter(u=>Ie[u]).map(u=>{const g=Ie[u];return{cat:u,label:g.label,metrics:g.metrics.filter(A=>i.includes(A.key))}}).filter(u=>u.metrics.length>0),[D,i]),C=b.useMemo(()=>{const u={};if(!z||z.length<=1)return u;for(const g of S)for(const A of g.metrics){if(A.fmt==="str")continue;const x=z.map(P=>P.metrics?.[A.key]).filter(P=>P!=null&&typeof P=="number");x.length!==0&&(u[A.key]=A.lowerBetter?Math.min(...x):Math.max(...x))}return u},[z,S]);return e.jsxs("div",{className:"p-3 md:p-6 max-w-7xl mx-auto space-y-4 md:space-y-6",children:[e.jsxs("button",{onClick:()=>t("/"),className:"flex items-center gap-1 text-sm text-slate-500 hover:text-slate-800",children:[e.jsx(Kt,{size:14})," Back to facilities"]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800",children:"Compare SNFs"}),e.jsx("p",{className:"text-sm text-slate-500 mt-1",children:"Select facilities and metrics to compare side-by-side"})]}),e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsxs("form",{onSubmit:u=>{u.preventDefault(),c(n)},className:"flex gap-3 mb-3",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(Jt,{size:15,className:"absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:n,onChange:u=>r(u.target.value),placeholder:"Search facility name or zip...",className:"w-full pl-9 pr-3 py-2 border border-slate-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-sky-500"})]}),e.jsxs("select",{value:l,onChange:u=>o(u.target.value),className:"border border-slate-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-sky-500",children:[e.jsx("option",{value:"",children:"All States"}),["AL","AK","AZ","AR","CA","CO","CT","DE","FL","GA","HI","ID","IL","IN","IA","KS","KY","LA","ME","MD","MA","MI","MN","MS","MO","MT","NE","NV","NH","NJ","NM","NY","NC","ND","OH","OK","OR","PA","RI","SC","SD","TN","TX","UT","VT","VA","WA","WV","WI","WY"].map(u=>e.jsx("option",{value:u,children:u},u))]}),e.jsx("button",{type:"submit",className:"bg-sky-600 hover:bg-sky-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors",children:"Search"})]}),j.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[(z||[]).map(u=>e.jsxs("span",{className:"inline-flex items-center gap-1 bg-sky-50 text-sky-700 px-3 py-1 rounded-full text-xs font-medium",children:[u.provider_name,"
6(",u.state,")",e.jsx("button",{onClick:()=>f(u.ccn),"aria-label":`Remove ${u.provider_name}`,className:"hover:text-red-500",children:e.jsx(Me,{size:12})})]},u.ccn)),j.filter(u=>!z?.find(g=>g.ccn===u)).map(u=>e.jsxs("span",{className:"inline-flex items-center gap-1 bg-slate-100 text-slate-500 px-3 py-1 rounded-full text-xs",children:[u,e.jsx("button",{onClick:()=>f(u),"aria-label":`Remove ${u}`,className:"hover:text-red-500",children:e.jsx(Me,{size:12})})]},u))]}),w?.results?.length>0&&d&&e.jsx("div",{className:"border border-slate-200 rounded-lg max-h-48 overflow-y-auto divide-y divide-slate-100",children:w.results.map(u=>e.jsxs("button",{onClick:()=>M(u.ccn),disabled:j.includes(u.ccn),className:`w-full text-left px-3 py-2 text-sm hover:bg-sky-50 flex justify-between items-center ${j.includes(u.ccn)?"opacity-40":""}`,children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-slate-700",children:u.provider_name}),e.jsxs("p",{className:"text-xs text-slate-400",children:[u.ccn," · ",u.citytown,", ",u.state," · ",u.number_of_certified_beds," beds"]})]}),!j.includes(u.ccn)&&e.jsx("span",{className:"text-xs text-sky-600",children:"+ Add"})]},u.ccn))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[Object.entries(Ie).map(([u,{label:g,metrics:A}])=>{const x=A.map(F=>F.key),P=x.filter(F=>i.includes(F)).length,$=P===x.length,T=P>0;return e.jsxs("button",{onClick:()=>y(u),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${$?"bg-sky-600 text-white border-sky-600":T?"bg-sky-100 text-sky-700 border-sky-300":"bg-white text-slate-600 border-slate-300 hover:border-sky-400 hover:text-sky-600"}`,children:[g,T&&!$?` (${P}/${x.length})`:""]},u)}),e.jsxs("button",{onClick:()=>p(u=>!u),className:"px-3 py-1.5 rounded-full text-xs font-medium border border-slate-300 bg-white text-slate-500 hover:border-sky-400 hover:text-sky-600 transition-colors flex items-center gap-1",children:[e.jsx(ua,{size:12})," Customize",m?e.jsx(Ae,{size:12}):e.jsx(ye,{size:12})]})]}),m&&e.jsxs("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm p-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:Object.entries(Ie).map(([u,{label:g,metrics:A}])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-bold text-slate-500 uppercase tracking-wide mb-2",children:g}),e.jsx("div",{className:"space-y-1",children:A.map(x=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer group",children:[e.jsx("input",{type:"checkbox",checked:i.includes(x.key),onChange:()=>L(x.key),className:"rounded border-slate-300 text-sky-600 focus:ring-sky-500 h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs text-slate-600 group-hover:text-slate-800",children:x.label})]},x.key))})]},u))}),e.jsxs("div",{className:"flex gap-3 mt-3 pt-3 border-t border-slate-100",children:[e.jsx("button",{onClick:()=>{const u=[...zo];h(u),v(u)},className:"text-xs text-sky-600 hover:text-sky-800 font-medium",children:"Select All"}),e.jsx("button",{onClick:()=>{h(ut),v(ut)},className:"text-xs text-slate-500 hover:text-slate-700 font-medium",children:"Reset to Default"})]})]})]}),_&&e.jsxs("div",{className:"flex items-center gap-2 text-slate-400 py-8 justify-center",children:[e.jsx(ge,{size:18,className:"animate-spin"})," Loading comparison..."]}),z?.length>0&&e.jsx("div",{className:"bg-white rounded-xl border border-slate-200 shadow-sm overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 border-b border-slate-200",children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",className:"text-left px-4 py-2 text-xs font-semibold text-slate-500 uppercase sticky left-0 bg-slate-50 z-10",children:"Metric"}),z.map(u=>e.jsxs("th",{scope:"col",className:"text-right px-4 py-2 text-xs font-semibold text-slate-700 min-w-[120px] md:min-w-[160px]",children:[e.jsx("button",{onClick:()=>{Zs(z.map(g=>g.ccn)),t(`/facility/${u.ccn}`)},className:"hover:text-sky-600 hover:underline text-right",children:u.provider_name}),e.jsxs("p",{className:"text-slate-400 font-normal",children:[u.citytown,", ",u.state,u.chain_name?` · ${u.chain_name}`:""]})]},u.ccn))]})}),e.jsx("tbody",{children:S.map(u=>e.jsxs(b.Fragment,{children:[e.jsx("tr",{className:"bg-slate-100 border-t border-slate-200",children:e.jsx("td",{colSpan:1+z.length,className:"px-4 py-2 text-xs font-bold text-slate-500 uppercase tracking-wide sticky left-0 bg-slate-100 z-10",children:u.label})}),u.metrics.map(g=>{const A=Eo[g.fmt]||Aa;return e.jsxs("tr",{className:"hover:bg-slate-50 border-t border-slate-100",children:[e.jsx("td",{className:"px-4 py-2.5 text-slate-600 font-medium sticky left-0 bg-white z-10 whitespace-nowrap",children:g.label}),z.map(x=>{const P=x.metrics?.[g.key],$=z.length>
61&&P!=null&&C[g.key]!=null&&P===C[g.key];return e.jsx("td",{className:`px-4 py-2.5 text-right ${$?"text-emerald-600 font-bold":"text-slate-700"}`,children:A(P)},x.ccn)})]},g.key)})]},u.cat))})]})}),j.length===0&&e.jsxs("div",{className:"bg-slate-50 border border-slate-200 rounded-xl p-12 text-center",children:[e.jsx(ea,{size:32,className:"mx-auto text-slate-300 mb-3"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Search and add facilities above to compare them side-by-side"})]})]})}export{mc as FacilityComparePage,xc 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.